Sub topic 2
Racing Futures with `select!`
Assume basic Rust ownership, borrowing, Future, async/await, Tokio tasks, and mpsc channels.
Racing futures with `select!`
tokio::select! waits for several asynchronous operations at once. It evaluates each branch and runs the first branch whose future becomes ready. The other branch futures are dropped.
use std::time::Duration;
use tokio::{
sync::mpsc,
time::{sleep, timeout},
};
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(8);
tokio::spawn(async move {
sleep(Duration::from_millis(40)).await;
tx.send("message").await.unwrap();
});
tokio::select! {
value = rx.recv() => println!("received: {value:?}"),
result = timeout(Duration::from_millis(20), sleep(Duration::from_secs(1))) => {
println!("timer result: {result:?}");
}
}
}The select! expression produces the result of its chosen branch. A branch can also contain a pattern, such as Some(value) = rx.recv(). If the pattern does not match, that branch is disabled for that invocation.
Cancel safety
Dropping a future cancels the operation represented by that future. Therefore, a losing select! branch may stop halfway through its work.
An operation is cancel safe when dropping it does not lose or corrupt progress. mpsc::Receiver::recv is cancel safe: if it loses a race, the message remains in the channel. Interval::tick is also designed for this use.
A future that removes an item from a queue and then awaits before finishing may not be cancel safe. If it loses the race after removal, the item could disappear. Move the removal and state update into a non-awaiting section, or use an API that first reserves a resource and commits only after the operation wins.
`select!` in loops
A future created inside a loop starts over on every iteration. That is often correct for recv and tick, but it is wrong for one overall deadline. Create the timer once, pin it, and poll it by mutable reference:
let deadline = sleep(Duration::from_secs(1));
tokio::pin!(deadline);
loop {
tokio::select! {
Some(message) = rx.recv() => println!("{message}"),
_ = &mut deadline => {
println!("deadline reached");
break;
}
}
}tokio::pin! lets the loop safely reuse the same future. A pattern such as Some(message) disables the receive branch after the channel closes. An if condition can disable a branch until a separate condition becomes true.
Exercise
Why must a reusable timer be polled as &mut deadline?
Show answer
select! may poll the timer repeatedly, so mutable pinned access preserves the same future and its elapsed state.