Sub topic 10
Waiting on several futures with join! and select!
This chapter assumes you know async fn and .await, can start a Tokio runtime with #[tokio::main], and understand tokio::spawn. It covers two macros that combine futures inside a single task: join! waits for all of them, and select! waits for the first.
Why not just await in order?
Awaiting two futures one after the other runs them one after the other. If each takes 100 ms, the total is about 200 ms. Often the futures are independent, and you want their waits to overlap.
join!: wait for all
tokio::join! polls every future it is given and returns a tuple of their outputs once all have finished.
use std::time::Duration;
use tokio::time::sleep;
async fn fetch(id: u32) -> u32 {
sleep(Duration::from_millis(100)).await;
id * 2
}
#[tokio::main]
async fn main() {
let (a, b) = tokio::join!(fetch(1), fetch(2));
println!("{a} {b}");
}This finishes in about 100 ms. The futures run concurrently but not in parallel, because join! runs them all inside the current task. They interleave on one thread whenever one of them reaches an .await and yields. If you need parallelism across worker threads, use tokio::spawn.
Because the futures stay in the current task, they can borrow local data. They do not need to be 'static or Send.
For fallible futures, tokio::try_join! returns early with the first Err and drops the rest.
select!: wait for the first
tokio::select! waits for the first branch to complete, runs that branch's handler, and drops the other futures.
use std::time::Duration;
use tokio::sync::oneshot;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let (tx, rx) = oneshot::channel::<()>();
tokio::spawn(async move {
sleep(Duration::from_millis(100)).await;
let _ = tx.send(());
});
tokio::select! {
_ = sleep(Duration::from_millis(500)) => println!("timed out"),
_ = rx => println!("signal received"),
}
}Here the signal arrives after 100 ms, so the 500 ms timer is dropped before it fires. The output is signal received.
Common errors
- Assuming
join!is parallel. One slow synchronous call inside any branch blocks all the others, because they share a task. - Forgetting that
select!drops the losers. A dropped future stops at its last.await. Work it had partly done is lost unless the future is cancel safe. Chapter material on cancellation covers this in detail. - Recreating futures in a loop. If you call
select!in a loop withsleep(...)written inline, the timer restarts on every iteration. Create the future once, pin it, and pass&muttoselect!if it should persist. - Ignoring the pattern. A branch like
Some(x) = rx.recv()is disabled when the pattern fails to match. If every branch is disabled,select!panics unless you add anelsebranch.
A simpler option for timeouts
When you only need to bound one future by a deadline, tokio::time::timeout is shorter than a two-branch select!. It returns Err(Elapsed) if the deadline passes first.
Exercise
You write let (a, b) = tokio::join!(task_one(), task_two()); and both functions call std::thread::sleep(Duration::from_millis(100)) instead of tokio::time::sleep. About how long does the line take, and why?
Show answer
About 200 ms. std::thread::sleep blocks the thread without yielding, so join! cannot switch to the other future while the first one sleeps. The two futures run one after the other. Using tokio::time::sleep(...).await would let them overlap and finish in about 100 ms.
Exercise
In a select! with branches _ = sleep(500ms) and _ = rx where rx completes first, what happens to the sleep future?
Show answer
It is dropped without completing, so the timer is cancelled and its handler never runs.