Sub topic 8
Spawning tasks and joining their handles
This chapter assumes you can write async fn and .await, and that you can start a Tokio runtime with #[tokio::main]. It also assumes you know what move closures and Result do. The Send and 'static requirements for spawned futures get their own chapter, so here they appear only when they affect the code.
What `tokio::spawn` does
Awaiting a future runs it inside the current task. Nothing else makes progress in that task while you wait. tokio::spawn works differently. It hands the future to the runtime as a new, independent task. A task is a unit of work that the runtime schedules by itself. The call returns immediately with a JoinHandle<T>, where T is the future's output type.
Three facts follow from this:
- The task starts running as soon as a worker thread is free, whether or not anyone awaits the handle.
- On Tokio's multi-threaded runtime, different tasks can run on different threads at the same time.
- The handle is how you get the result back.
A first spawn
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(50)).await;
println!("task done");
42
});
println!("main continues");
let value = handle.await.unwrap();
println!("value = {value}");
}The output is main continues, then task done, then value = 42. Unlike the lazy future from the earlier chapter, the spawned future runs without being awaited. Awaiting the handle only waits for it to finish and collects its output.
Why the handle returns a `Result`
handle.await has type Result<T, JoinError>, not T. The task can end in a way that produces no value:
- The task panicked. A panic inside a spawned task is caught by the runtime, and the other tasks keep running.
- The task was cancelled, for example by
abort()or by runtime shutdown.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
let v: Vec<u32> = Vec::new();
v[0]
});
match handle.await {
Ok(v) => println!("value {v}"),
Err(e) if e.is_panic() => println!("task panicked"),
Err(e) => println!("task failed: {e}"),
}
}Calling unwrap() on the result turns a panic in the child into a panic in the parent. That is fine in examples. In real code, decide whether a crashed child should take down the parent. JoinError::into_panic() gives you the original panic payload if you want to re-raise it.
Do not confuse JoinError with errors your task returns. If the future's output is itself a Result, you get a nested Result<Result<T, E>, JoinError>. The outer layer is "did the task finish normally" and the inner layer is "did the work succeed".
Spawning many tasks
Collect the handles in a Vec, then await them in order.
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 - id * 30)).await;
id * 10
}));
}
for handle in handles {
println!("{}", handle.await.unwrap());
}
}All three tasks run concurrently, so the total time is about 100 ms, not 220 ms. The output is 0, 10, 20 even though task 2 finishes first. You are awaiting handles in spawn order, so results come back in spawn order. The async move block copies id into each task. Without move, the block would borrow id from the loop, and a spawned task cannot borrow from the function that spawned it.
`JoinSet` for results in completion order
When you want each result as soon as it is ready, use tokio::task::JoinSet.
use std::time::Duration;
use tokio::task::JoinSet;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for id in 0..3u64 {
set.spawn(async move {
sleep(Duration::from_millis(100 - id * 40)).await;
id
});
}
while let Some(res) = set.join_next().await {
println!("finished {}", res.unwrap());
}
}This prints finished 2, finished 1, finished 0. A JoinSet also aborts all of its remaining tasks when you drop it. A loose Vec<JoinHandle<_>> does not do that.
Detaching and aborting
Dropping a JoinHandle does not cancel the task. It detaches it: the task keeps running and its result is discarded. This is the opposite of dropping a plain future, which cancels it. To stop a task, call abort() explicitly.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_secs(60)).await;
});
handle.abort();
let err = handle.await.unwrap_err();
println!("cancelled: {}", err.is_cancelled());
}This prints cancelled: true. An aborted task stops at its next .await. Code between two awaits always runs to completion, so a task stuck in a loop with no .await cannot be aborted.
`spawn` compared with `join!`
| Row | `tokio::join!` | `tokio::spawn` |
|---|---|---|
| Where the futures run | Inside the current task | In new, separate tasks |
| Parallel across threads | No, one task is polled at a time | Yes, on the multi-threaded runtime |
| Can borrow local data | Yes | No, the future must be `'static` |
| Starts without being awaited | No | Yes |
| Panic behavior | Propagates to the current task | Captured in `JoinError` |
Use join! for a fixed, small set of operations that belong together and may borrow locals. Use spawn when work should outlive the current scope, run in parallel on several threads, or fail without taking its parent down.
Common mistakes
- Awaiting inside the spawn loop. Writing
tokio::spawn(...).awaitin the loop body runs the tasks one after another. Push the handle first and await later. - Forgetting the handle. A task whose panic nobody observes fails silently, apart from a message on stderr. Keep the handle if you care about the outcome.
- Spawning for trivial work. A task has a small allocation cost and a scheduling cost. Spawning one per tiny operation is wasteful when
join!would do. - Borrowing locals. Compiler errors such as "borrowed value does not live long enough" or "closure may outlive the current function" mean you need
async move, a clone, or anArc.
Exercise
A function spawns a task that writes a log file, then drops the returned JoinHandle without awaiting it and returns. Does the task still run? What happens if the whole program exits right after?
Show answer
Yes. Dropping a JoinHandle detaches the task, so it keeps running and its result is discarded. If the program exits first (main returns and the runtime shuts down), the task is dropped at its next await point and may not finish writing. To guarantee completion, keep the handle and await it, or use a JoinSet and drain it before exiting.
Exercise
What is the type of handle.await when the spawned future is async { Ok::<u32, std::io::Error>(5) }, and how do you get the u32 safely?
Show answer
It is Result<Result<u32, std::io::Error>, JoinError>. The outer Result reports whether the task finished normally (not panicked or cancelled), and the inner one reports the task's own success or failure. Handle both layers, for example with match handle.await { Ok(Ok(n)) => ..., Ok(Err(io_err)) => ..., Err(join_err) => ... }.