Sub topic 10
Waiting on several futures with join! and select!
This chapter assumes you can write basic async fn code, run it under #[tokio::main], and use tokio::spawn and JoinHandle. It also assumes you know that .await on a future suspends only the current task. It covers how to wait on several futures from one task, and the cases where you would pick join!, select! or timeout over spawning.
Why one `.await` at a time is not enough
Awaiting futures one after another runs them in sequence:
let a = fetch(1).await;
let b = fetch(2).await;If each call waits 100 ms, this takes about 200 ms. The second future does not start until the first one finishes. Tokio offers two macros that poll several futures from the same task.
join!waits for all of them.select!waits for the first one and drops the rest.
Neither macro creates a new task. All the futures are polled by the task that runs the macro. They interleave on one thread at a time, so you get concurrency but not parallelism.
join!: wait for everything
tokio::join! takes several futures and returns a tuple of their outputs, in the order you wrote them.
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}");
}The total time is about 100 ms. Both sleeps are registered with the timer, and the task wakes when either is ready.
The number of futures is fixed when you write the code. If you have a Vec of futures, use futures::future::join_all from the futures crate, or spawn the work and collect JoinHandles.
try_join!: stop at the first error
When the futures return Result, tokio::try_join! returns early with the first Err. It drops the futures that are still pending. On success it returns a tuple of the Ok values.
use std::time::Duration;
use tokio::time::sleep;
async fn load(name: &'static str, delay_ms: u64, ok: bool) -> Result<String, String> {
sleep(Duration::from_millis(delay_ms)).await;
if ok {
Ok(format!("{name} loaded"))
} else {
Err(format!("{name} failed"))
}
}
#[tokio::main]
async fn main() {
let result = tokio::try_join!(
load("config", 50, true),
load("cache", 20, false),
load("index", 500, true),
);
match result {
Ok((a, b, c)) => println!("{a}, {b}, {c}"),
Err(e) => println!("aborted: {e}"),
}
}Here cache fails after 20 ms. try_join! returns that error at once, and the 500 ms index future is dropped without finishing. The error types of all the futures must be the same, or convertible with ?-style From conversion.
select!: first one wins
tokio::select! polls several branches. When one completes, it runs that branch's handler and drops every other branch's future.
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"),
}
}Each branch has the form pattern = future => handler. The handler can use the value bound by the pattern. All handlers must evaluate to the same type, because select! is an expression.
Branch preconditions and patterns
A branch can be guarded with , if condition. If the condition is false, the branch is not polled. A branch can also use a refutable pattern such as Some(x) = rx.recv(). If the result does not match, that branch is disabled for the current select! call. If every branch is disabled, select! runs the optional else => branch. Without an else branch, that situation panics.
Fairness and `biased;`
By default select! picks a random starting branch on each call. This prevents one always-ready branch from starving the others. If you start the macro with biased;, branches are polled in the order written. Use that only when the order matters, for example to check a shutdown signal before taking new work, and keep in mind that it can starve later branches.
select! inside a loop
A common pattern is to receive messages until a deadline. A future you want to keep across loop iterations must be pinned and polled by mutable reference. Otherwise each iteration would create a fresh timer.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(4);
tokio::spawn(async move {
for i in 0..3 {
tx.send(i).await.unwrap();
sleep(Duration::from_millis(50)).await;
}
});
let deadline = sleep(Duration::from_millis(500));
tokio::pin!(deadline);
loop {
tokio::select! {
maybe = rx.recv() => match maybe {
Some(n) => println!("got {n}"),
None => {
println!("channel closed");
break;
}
},
_ = &mut deadline => {
println!("deadline reached");
break;
}
}
}
}rx.recv() creates a new future on each iteration, which is fine because it is cancel safe. &mut deadline keeps one Sleep alive, so the 500 ms countdown is not reset each time a message arrives. tokio::pin! fixes the future in place, which the &mut form requires.
timeout: select! with a clock
Racing a future against a timer is common enough that Tokio wraps it as tokio::time::timeout. It returns Ok(output) if the future finishes in time, and Err(Elapsed) if not. When it times out, the inner future is dropped.
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::main]
async fn main() {
let slow = sleep(Duration::from_secs(1));
match timeout(Duration::from_millis(50), slow).await {
Ok(_) => println!("finished"),
Err(_) => println!("timed out"),
}
}Choosing between join!, select! and spawn
| Need | Use | Notes |
|---|---|---|
| All results, fixed set of futures | `join!` | One task, no `'static` or `Send` bound on the futures |
| All results, stop on first error | `try_join!` | Remaining futures are dropped |
| First result only | `select!` | Losers are dropped |
| Give up after a time limit | `timeout` | Wraps one future |
| True parallelism across threads | `tokio::spawn` | Each future becomes its own task and must be `Send + 'static` |
Because join! keeps everything in one task, the futures can borrow local variables, which a spawned task cannot do. The cost is that a future that blocks the thread, or does a long stretch of CPU work between .await points, delays all the others in the same macro.
Edge cases and common errors
- Dropping is cancellation. A branch that loses a
select!race is dropped at its last.await. Any work it did before that point is lost. This is the main reason cancel safety matters, and the next chapters return to it. - Cancel-unsafe futures in loops. If a future loses a race after consuming part of its input, that input can be lost. Before putting a method in a
select!loop, check whether its documentation says it is cancel safe.mpsc::Receiver::recvis. A hand-writtenread_exactloop usually is not. - Side effects in handlers. Handlers run after the race is decided, but the branch futures can already have done some of their work. Keep the futures simple and put side effects in the handlers.
- Panic with no branches. If all branches are disabled and there is no
else,select!panics. - Starving other branches. With
biased;, an always-ready first branch means later branches are never polled. - Blocking inside a branch.
std::thread::sleepin one future stalls every sibling future, because they share the task's thread.
Exercises
Exercise
You run tokio::join!(a(), b()), where a and b each take 100 ms of tokio::time::sleep. What is the approximate total time, and what would it be if you wrote a().await; b().await; instead?
Show answer
About 100 ms with join!, because both sleeps are pending at the same time inside one task. The sequential version takes about 200 ms, because b does not start until a completes.
Exercise
In a loop, you want to receive from rx but stop 2 seconds after the loop started, no matter how many messages arrive. Why must the sleep(Duration::from_secs(2)) be created outside the loop and pinned, with &mut deadline used in the select!?
Show answer
A sleep(...) expression inside the select! creates a new timer on every iteration, so each received message would restart the 2-second countdown and the deadline would never fire. Creating it once, pinning it with tokio::pin!, and polling &mut deadline keeps a single timer running across iterations.
Exercise
What does tokio::try_join! do with the futures that are still running when one of them returns Err?
Show answer
It returns that error immediately and drops the unfinished futures, which cancels them at their current .await point.