Sub topic 5
Racing futures with select!
This chapter assumes you know basic Rust ownership and the Drop trait, async/await syntax, tokio::spawn, and tokio::sync::mpsc. You should also know that dropping a future cancels it, which the previous chapters covered. The examples need tokio = { version = "1", features = ["full"] } in Cargo.toml. The tokio-util crate appears in later chapters.
What select! does
tokio::select! waits on several futures at once and finishes when the first one completes. It then drops every other future and runs the handler for the winner. The whole macro is an expression, so it produces a value.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let winner = tokio::select! {
_ = sleep(Duration::from_millis(200)) => "slow",
_ = sleep(Duration::from_millis(50)) => "fast",
};
println!("{winner}");
}This prints fast. Each branch has the form pattern = future => handler. The future expression is the part after =. The handler is the part after =>. Every handler must evaluate to the same type, because the macro returns whichever handler ran.
How select! runs
All branches run inside the task that executes the select!. No new tasks are created. The macro polls each branch in turn, and when none is ready it returns Pending for the whole expression. Any branch that becomes ready wakes the task, and the macro polls again.
This has three consequences:
- Branches take turns on one thread. They are concurrent, not parallel.
- A branch that blocks the thread, for example with
std::thread::sleep, stops every other branch. A later chapter covers this. - No
ArcorMutexis needed to share local variables between handlers, because everything runs in one task.
The sequence below shows what happens inside one select!.
Losing branches are dropped
The losing futures are dropped before the winner's handler runs. This example makes that visible with a type that prints when dropped.
use std::time::Duration;
use tokio::time::sleep;
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
async fn job(name: &'static str, ms: u64) -> &'static str {
let _guard = Noisy(name);
sleep(Duration::from_millis(ms)).await;
name
}
#[tokio::main]
async fn main() {
let result = tokio::select! {
r = job("a", 50) => r,
r = job("b", 500) => r,
};
println!("winner: {result}");
}The output is:
dropping a
dropping b
winner: aJob a finishes and drops its guard as it returns. The select! then drops job b while it is suspended at its sleep, so b never reaches its last line. Job b stops at its await point and its destructors run. This is the same mechanism timeout uses.
Because the futures are gone before any handler runs, a handler can freely use variables that a future borrowed.
Relationship to timeout
timeout(d, fut) is a specialised two-branch race between fut and a timer. You can write the same thing by hand, which is useful once you need different behaviour on each side.
use std::time::Duration;
use tokio::time::sleep;
async fn fetch() -> u32 {
sleep(Duration::from_millis(300)).await;
42
}
#[tokio::main]
async fn main() {
let result = tokio::select! {
v = fetch() => Some(v),
_ = sleep(Duration::from_millis(100)) => None,
};
println!("{result:?}");
}This prints None. Both handlers return Option<u32>, so the types match. Use timeout when you only need a deadline. Use select! when the other branch is something else, such as a shutdown signal or a second data source.
Patterns, preconditions, and else
The left side of a branch is a full pattern. If the future's output does not match, that branch is disabled for the rest of this select!, and the others keep running.
use tokio::sync::oneshot;
#[tokio::main]
async fn main() {
let (tx1, rx1) = oneshot::channel::<u32>();
let (tx2, rx2) = oneshot::channel::<u32>();
drop(tx1); // rx1 resolves to Err(RecvError)
tokio::spawn(async move {
let _ = tx2.send(7);
});
tokio::select! {
Ok(v) = rx1 => println!("rx1 sent {v}"),
Ok(v) = rx2 => println!("rx2 sent {v}"),
else => println!("every branch was disabled"),
}
}The first receiver yields Err, which does not match Ok(v), so that branch is disabled. The second branch then wins and the program prints rx2 sent 7. If both patterns had failed, the else handler would run.
An if precondition disables a branch before polling starts:
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let use_fast_path = false;
tokio::select! {
_ = sleep(Duration::from_millis(10)), if use_fast_path => println!("fast path"),
_ = sleep(Duration::from_millis(100)) => println!("normal path"),
}
}This prints normal path. The precondition is checked each time the select! starts. When it is false, the future expression is still evaluated, but the resulting future is never polled. Avoid side effects in an expression whose branch may be disabled.
Fairness and biased
By default select! picks a random branch to poll first on each call. This stops one always-ready branch from starving the others. Adding biased; as the first line switches to top-to-bottom order.
#[tokio::main]
async fn main() {
tokio::select! {
biased;
_ = std::future::ready(()) => println!("first"),
_ = std::future::ready(()) => println!("second"),
}
}This always prints first. Without biased;, either line could print. Use biased; when priority matters, for example to check a shutdown signal before taking more work. The cost is starvation. If the first branch is always ready, the later ones never run.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Compile error about mismatched types | The handlers return different types | Make every handler return the same type, or end each with `;` and `()` |
| Panic: all branches are disabled | Every pattern failed or every precondition was false, and there is no `else` | Add an `else` branch |
| Other branches stall | One handler or future blocks the thread | Keep handlers short, and move blocking work off the runtime |
| Work continues after losing a race | The losing branch was a `JoinHandle`, not the work itself | Abort the task explicitly |
| Messages vanish when a branch loses | The dropped future held data that was not cancel safe | See the next chapter on cancel safety |
| Same result every run, other branches starve | `biased;` with an always-ready first branch | Reorder the branches, or remove `biased;` |
What this chapter leaves open
Two questions come up as soon as you use select! for real work. The first is which futures lose nothing when they are dropped halfway. Some operations, such as mpsc::Receiver::recv, are safe to drop and retry. Others can discard data you already took. The next chapter covers this under the name cancel safety. The second question is how to use select! inside a loop without recreating a long-lived future, such as a deadline, on every iteration. That needs pinning and polling by &mut, which a later chapter on select loops explains.
Exercise
What does this program print, and in what order? Explain why. use std::time::Duration; use tokio::time::sleep; struct Noisy(&'static str); impl Drop for Noisy { fn drop(&mut self) { println!("drop {}", self.0); } } #[tokio::main] async fn main() { tokio::select! { = async { let g = Noisy("left"); sleep(Duration::frommillis(10)).await; } => println!("left won"), = async { let g = Noisy("right"); sleep(Duration::frommillis(500)).await; } => println!("right won"), } }
Show answer
It prints "drop left", then "drop right", then "left won". The left block finishes after 10 ms and its guard drops as the block ends. The select! then drops the right block while it is suspended at its sleep, which runs the right guard's destructor. The handler runs only after all futures are gone, so "left won" comes last. "right won" never prints.
Exercise
You write select! with two branches. The first has the pattern Some(msg) on rx.recv(). The second is _ = shutdown.recv(). There is no else branch. The channel behind rx closes while shutdown never fires. What happens, and how do you avoid a panic if both sources can end?
Show answer
When the channel closes, recv() returns None, which does not match Some(msg), so that branch is disabled. The select! keeps waiting on the shutdown branch. If shutdown also ends with a value that fails to match its pattern, no branch is left and select! panics because there is no else. Add an else branch that handles the case where every source has ended, for example by breaking out of the loop or returning.