-
I am very new to tokio and trying to understand it by writing small programs. In this program I want to see how much memory is allocated for very small tasks and if its reclaimed after the tasks are complete. In this program async fn process_one(i: i32) {
let delay_in_seconds = Duration::new(5, 0);
tokio::time::delay_for(delay_in_seconds).await;
println!("{}", i);
}
#[tokio::main]
async fn main() {
for i in 0..1_000_000 {
task::spawn(async move {
process_one(i).await;
});
}
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).expect("Ahhhh");
} In this program I spawn a million tasks where each task waits for 5 seconds, prints a number and then exits. This program works but I observe 2 things -
This is puzzling to me. Shouldn't the memory be freed after all the tasks are complete? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 5 replies
-
This is probably not a memory leak in Tokio, but Rust's memory allocator not releasing the memory back to the OS. If I run the loop several times with a sleep in between, the memory remains constant after the first run. |
Beta Was this translation helpful? Give feedback.
-
as @Darksonn states, this is Rust's memory allocator, you can confirm that using a tool like Heaptrack. use std::time::Duration;
use tokio::task;
use std::io;
async fn process_one(i: i32) {
let delay_in_seconds = Duration::new(5, 0);
tokio::time::delay_for(delay_in_seconds).await;
println!("{}", i);
}
#[tokio::main]
async fn main() {
for i in 0..1_000_000 {
task::spawn(async move {
process_one(i).await;
});
}
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).expect("Ahhhh");
} and analyzing with |
Beta Was this translation helpful? Give feedback.
-
Hey, sorry for waking this discussion up but I could also use some explanation please :) when I'm spawning 1 million tasks the memory goes back to 18.9MB compared to 808Kb when spawning 1000 tasks. Thanks a lot! |
Beta Was this translation helpful? Give feedback.
This is probably not a memory leak in Tokio, but Rust's memory allocator not releasing the memory back to the OS. If I run the loop several times with a sleep in between, the memory remains constant after the first run.