Sub topic 8
Collecting results and handling task panics
This chapter assumes you can spawn tasks with tokio::spawn, and that you know Rust's Result, Option, and ? operator. It covers how to get a value back from a task and what happens when the task fails.
What a JoinHandle gives you
tokio::spawn returns a JoinHandle<T>, where T is the output of the spawned future. Awaiting the handle yields Result<T, JoinError>. There are two layers of failure to keep apart:
- The task's own result. If the task returns
Result<U, E>, thenTis thatResult. - The
JoinError. This means the task did not finish normally. It either panicked or was cancelled.
use tokio::task::JoinHandle;
#[tokio::main]
async fn main() {
let handle: JoinHandle<Result<u32, String>> = tokio::spawn(async {
Err("bad input".to_string())
});
match handle.await {
Ok(Ok(n)) => println!("value {n}"),
Ok(Err(e)) => println!("task failed cleanly: {e}"),
Err(e) => println!("task did not finish: {e}"),
}
}The outer Err is a JoinError. The inner Err is your own error type.
Panics stay inside the task
A panic in a spawned task does not crash the program. Tokio catches it, ends only that task, and reports it through the handle. You can check with is_panic() and recover the payload with into_panic().
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
let v: Vec<u32> = Vec::new();
v[0]
});
match handle.await {
Ok(n) => println!("got {n}"),
Err(e) if e.is_panic() => println!("task panicked"),
Err(e) => println!("task was cancelled: {e}"),
}
}The default panic message is still printed to stderr. Only the unwinding is contained. This relies on panic = "unwind", which is the default. With panic = "abort" in your Cargo profile, a panic ends the whole process.
If you call .unwrap() on the handle result, a task panic becomes a panic in the awaiting task. That is sometimes what you want, but it is a choice, not a default.
Collecting many results
Spawn all tasks first, then await the handles. Awaiting inside the spawn loop would run the tasks one after another.
#[tokio::main]
async fn main() {
let handles: Vec<_> = (0..5u32)
.map(|i| tokio::spawn(async move { i * i }))
.collect();
let mut results = Vec::new();
for h in handles {
results.push(h.await.unwrap());
}
println!("{results:?}");
}Results come back in spawn order, because you await the handles in that order. If one early task is slow, later results wait behind it even if they finished first. Use tokio::task::JoinSet when you want results in completion order.
use tokio::task::JoinSet;
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for i in 0..5u32 {
set.spawn(async move { i * 10 });
}
while let Some(res) = set.join_next().await {
match res {
Ok(v) => println!("done {v}"),
Err(e) => eprintln!("task failed: {e}"),
}
}
}Dropping a JoinSet aborts the tasks still in it. Dropping a bare JoinHandle does not. It detaches the task, which keeps running.
Common errors
- Ignoring the handle. A failed task then goes unnoticed, because its panic is only visible to whoever awaits the handle.
- Confusing the two error layers.
handle.await?only handles theJoinError. You still have to deal with your own innerResult. - Awaiting each handle right after spawning it. This removes the concurrency.
- Expecting
abort()to stop a task instantly. A task is cancelled at its next.awaitpoint, so a task in a tight loop with no.awaitcannot be aborted.
Exercise
A spawned task has type JoinHandle<Result<u32, String>>. What does handle.await return, and which variant means the task panicked?
Show answer
It returns Result<Result<u32, String>, JoinError>. A panic appears as the outer Err(JoinError), where is_panic() is true. The inner Err(String) is an error your own code returned.
Exercise
Why might JoinSet::join_next be better than awaiting a Vec of handles in order?
Show answer
join_next returns each result as its task finishes, so a slow early task does not delay results from faster ones. Dropping the JoinSet also aborts any unfinished tasks.