Sub topic 7
Spawning tasks and joining their handles
This chapter assumes you know Rust ownership, closures with move, Result, and the basics of async fn and .await. It also assumes you have Tokio in Cargo.toml with the full feature.
What a task is
A task is a future that the runtime owns and drives on its own. tokio::spawn hands a future to the runtime and returns right away with a JoinHandle. The task starts running in the background, even if you never await the handle.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async { 1 + 2 });
let result = handle.await.unwrap();
println!("{result}");
}Awaiting the handle returns Result<T, JoinError>. T is the task's output. The Err case means the task panicked or was cancelled.
Spawn versus await
Awaiting a future directly runs it as part of the current task. Spawning makes a separate task that the scheduler can place on any worker thread.
Joining many tasks
Collect the handles in a Vec, then await each one. All tasks run at the same time, because each was already started by spawn.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let mut handles = Vec::new();
for id in 0..3u64 {
handles.push(tokio::spawn(async move {
sleep(Duration::from_millis(100 * (3 - id))).await;
id * 10
}));
}
for handle in handles {
let value = handle.await.unwrap();
println!("{value}");
}
}The output is 0, 10, 20 in order, because you await the handles in the order you stored them. The task with id 2 finishes first, but its result waits in the handle until you ask for it.
The async move block takes ownership of id. The next chapter explains why spawned tasks need this.
Handling a failed task
A panic inside a task does not crash the program. It shows up as a JoinError when you await the handle.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
if true {
panic!("boom");
}
5
});
match handle.await {
Ok(v) => println!("value {v}"),
Err(e) if e.is_panic() => println!("task panicked"),
Err(e) => println!("task failed: {e}"),
}
}If the task itself returns a Result, you get a nested Result<Result<T, E>, JoinError>. Handle the outer layer first, then the inner one.
Common mistakes
- Dropping a
JoinHandledoes not cancel the task. It only detaches it, so the task keeps running. - Calling
handle.abort()cancels the task. Awaiting it afterward gives aJoinErrorwhereis_cancelled()is true. - If
mainreturns, the runtime shuts down and any unfinished tasks are dropped. - Awaiting handles one by one in a loop is fine for collecting results. The tasks are already running, so the loop adds no delay.
Exercise
You spawn a task and then drop its JoinHandle without awaiting it. Does the task stop? What happens to its panic, if it panics?
Show answer
The task does not stop. Dropping a JoinHandle detaches the task, and it keeps running until it finishes or the runtime shuts down. A panic is caught by the runtime and not propagated, so nobody sees the JoinError unless a handle is awaited.