Sub topic 14
Composing futures: join, select, and spawn
This chapter assumes you know that a future is polled by an executor and that dropping a future cancels it. The examples use the tokio crate, since the standard library has no join!, select!, or spawn. Add tokio = { version = "1", features = ["full"] } to Cargo.toml.
Why composition matters
Calling .await twice in a row runs the two futures one after the other. To get concurrency, you need to give the executor more than one future to poll at the same time. There are two ways to do that. You can combine futures inside one task, or you can spawn separate tasks.
join: wait for all
join! polls several futures together and returns when all of them are done. It returns their outputs as a tuple.
use std::time::Duration;
use tokio::time::sleep;
async fn fetch(name: &str, ms: u64) -> String {
sleep(Duration::from_millis(ms)).await;
format!("{name} done")
}
#[tokio::main]
async fn main() {
let (a, b) = tokio::join!(fetch("a", 200), fetch("b", 100));
println!("{a}, {b}");
}This takes about 200 ms, not 300 ms. Both futures live inside the one future that join! creates, so they share a single task. They interleave at await points, but they never run on two threads at once.
select: first one wins
select! polls several futures and finishes when the first one completes. It then drops all the others.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::select! {
_ = sleep(Duration::from_millis(500)) => println!("slow won"),
_ = sleep(Duration::from_millis(50)) => println!("fast won"),
}
}Dropping a future cancels it, as the cancellation chapter explains. Anything the losing branch did before its last .await has already happened, and nothing after that point will run.
spawn: run independently
tokio::spawn hands a future to the runtime as its own task. The task starts running without being awaited. It can move between worker threads. You get back a JoinHandle, which you can await for the result.
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async { 21 * 2 });
let value = handle.await.unwrap();
println!("{value}");
}The future passed to spawn must be Send + 'static. It must be Send because the task may resume on a different thread. It must be 'static because it can outlive the function that spawned it, so it cannot borrow local variables. Use async move to move values in. await on the handle returns a Result, because the task may have panicked or been cancelled.
A spawned task keeps running if you drop its JoinHandle. Dropping the handle detaches the task. It does not cancel it.
Choosing between them
| Tool | Tasks | Needs `Send + 'static` | Ends when |
|---|---|---|---|
| `join!` | One | No | All futures finish |
| `select!` | One | No | First future finishes |
| `spawn` | One per call | Yes | The task finishes on its own |
Use join! when you need every result and the futures can borrow local data. Use select! for timeouts and shutdown signals. Use spawn when work should continue independently, or when you want it to run in parallel on several threads.
Exercise
Why does tokio::spawn(async { println!("{}", local_ref) }) fail to compile when local_ref is a &String borrowed from the calling function, and what is the usual fix?
Show answer
A spawned future must be 'static because the task can outlive the calling function, and a borrowed reference does not satisfy that. The usual fix is to move owned data into the task, for example by cloning the String or wrapping it in an Arc, and using async move.