Skip to content

Why does the task execute without await? #5202

Answered by Darksonn
khassar00 asked this question in Q&A
Discussion options

You must be logged in to vote

This is the difference between tokio::spawn and other futures. With most normal futures, they don't execute until you .await them, but tokio::spawn is different: the task starts executing in the background immediately, and using .await on the returned JoinHandle is just a way to wait for it to finish — it doesn't affect the execution of the task.

This means that this:

let mut handles = Vec::new();
for i in num_tasks {
    handles.push(tokio::spawn(start_task(i)));
}
let mut outputs = Vec::new();
for handle in handles {
    outputs.push(handle.await.unwrap());
}

will execute all num_tasks tasks in parallel, even though only one JoinHandle is .awaited at the time.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by hawkw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants