Sub topic 5
Racing futures with select!
This chapter assumes you know async/await, can spawn tasks on Tokio, and know that dropping a future cancels it. Earlier chapters covered that last point and timeout. Here you will use tokio::select! to wait on several futures and act on the first one that finishes.
What select! does
tokio::select! takes several async expressions, called branches. It polls all of them on the same task. When one completes, the macro drops every other branch's future and runs the handler of the winner. The result of the whole select! is the value of that handler.
Dropping the losers is the same cancellation you saw with timeout. timeout is effectively a select! between your future and a timer.
A first race
Each branch has the form pattern = future => handler.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
tokio::select! {
_ = sleep(Duration::from_millis(100)) => println!("fast branch won"),
_ = sleep(Duration::from_millis(500)) => println!("slow branch won"),
}
println!("done");
}This prints fast branch won, then done. The 500 ms sleep is dropped without ever finishing.
Using the result of a branch
The pattern on the left receives the future's output. You can bind it to a name and use it in the handler.
use std::time::Duration;
use tokio::{sync::oneshot, time::sleep};
#[tokio::main]
async fn main() {
let (tx, rx) = oneshot::channel::<&str>();
tokio::spawn(async move {
sleep(Duration::from_millis(50)).await;
let _ = tx.send("reply from worker");
});
let text = tokio::select! {
msg = rx => match msg {
Ok(m) => m.to_string(),
Err(_) => "sender dropped".to_string(),
},
_ = sleep(Duration::from_secs(1)) => "no reply in time".to_string(),
};
println!("{text}");
}Every handler must produce the same type, because select! returns one value.
Patterns, disabled branches, and else
If the pattern does not match the output, the branch is disabled for this select!. The macro keeps waiting on the other branches. If every branch is disabled, select! panics unless you provide an else branch.
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(4);
tx.send(7).await.unwrap();
drop(tx);
for _ in 0..2 {
tokio::select! {
Some(n) = rx.recv() => println!("got {n}"),
else => println!("channel closed, no branches left"),
}
}
}The first pass prints got 7. On the second pass recv() returns None, the Some(n) pattern fails, the only branch is disabled, and else runs.
Handlers run after the race
Once a winner is chosen, the other futures are already dropped. The handler can use .await, borrow variables mutably, and use break, continue, or return from the enclosing function. Handlers are not polled concurrently with the other branches, so a slow handler delays nothing that is still racing, because nothing is.
The branch expressions, by contrast, all run on one task. They never run in parallel. If you need parallelism, spawn tasks and race their JoinHandles.
Fairness and biased
By default select! picks a random starting branch each time it polls. That prevents one always-ready branch from starving the others. Add biased; as the first line to poll branches in the order written.
use tokio::sync::mpsc;
async fn drain(mut urgent: mpsc::Receiver<u32>, mut normal: mpsc::Receiver<u32>) {
loop {
tokio::select! {
biased;
Some(n) = urgent.recv() => println!("urgent {n}"),
Some(n) = normal.recv() => println!("normal {n}"),
else => break,
}
}
}Use biased; when order matters, such as checking a shutdown signal first. The cost is that an early branch that is always ready can starve later ones.
Common mistakes
- Racing a future that loses data when dropped. Whether a loser is safe to drop is called cancel safety, covered in the next chapter.
- Doing long synchronous work in a branch expression. Nothing else on that task can make progress while it runs.
- Forgetting
elsewhen all branches could be disabled, which causes a panic.
Exercise
In tokio::select! { a = fut_a => handle_a(a), b = fut_b => handle_b(b) }, what happens to fut_b if fut_a completes first, and what must be true of handle_a and handle_b?
Show answer
fut_b is dropped, which cancels it at its current await point. handle_a and handle_b must return the same type, because the select! expression evaluates to the winning handler's value.