Sub topic 7
select! in loops: pinning, resuming, and disabled branches
This chapter assumes you know the basics of tokio::select!, that dropping a future cancels it, and what cancel safety means. You should also be comfortable with tokio::sync::mpsc and tokio::spawn.
The problem with loops
select! drops every branch future that loses the race. In a loop, that happens on every iteration. If a branch expression such as sleep(...) is written inside select!, a new future is created each time around the loop. A deadline written that way restarts on every message, so it never fires if messages keep arriving.
Two tools fix this: create the future once outside the loop, and poll it by mutable reference.
Keeping one deadline across iterations
Create the Sleep future before the loop and pin it with tokio::pin!. Then pass &mut deadline to select!. Polling through a reference means the future is not moved into the macro, so losing a race does not drop it. The next iteration resumes the same timer.
use std::time::Duration;
use tokio::{sync::mpsc, time::sleep};
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
for i in 0..5 {
let _ = tx.send(i).await;
sleep(Duration::from_millis(40)).await;
}
});
let deadline = sleep(Duration::from_millis(150));
tokio::pin!(deadline);
loop {
tokio::select! {
Some(n) = rx.recv() => println!("got {n}"),
_ = &mut deadline => {
println!("overall deadline reached");
break;
}
}
}
}Pinning is required because &mut F implements Future only when F is Unpin. A Sleep is not Unpin, so tokio::pin! fixes it in place on the stack and gives you a Pin<&mut Sleep>. Passing &mut deadline then works.
Resuming a future that is not cancel safe
The same technique helps when a branch future is not cancel safe. If you create it once and poll it by &mut, a lost race does not drop it, so its partial progress survives. This is why the pattern appears with long-running operations that you want to continue after handling another event.
Once a future completes, do not poll it again. Most futures panic if polled after completion. That leads to the next concern.
Disabled branches and preconditions
In the example above, the pattern Some(n) = rx.recv() does more than unpack a value. If recv() returns None, the pattern does not match. select! then disables that branch for the rest of the call and waits on the others. If every branch is disabled, select! panics, unless you supply an else branch.
An else branch runs when all branches are disabled. It gives the loop a clean exit:
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(4);
tx.send(1).await.unwrap();
tx.send(2).await.unwrap();
drop(tx);
loop {
tokio::select! {
Some(n) = rx.recv() => println!("got {n}"),
else => {
println!("all branches disabled");
break;
}
}
}
}You can also disable a branch yourself with a precondition: value = fut, if enabled => .... The expression after if is checked before polling. When it is false, the branch is skipped for that select! call. Preconditions are useful when a pinned future has already completed and must not be polled again.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let timer = sleep(Duration::from_millis(50));
tokio::pin!(timer);
let mut done = false;
let mut rounds = 0;
while rounds < 3 {
tokio::select! {
_ = &mut timer, if !done => {
println!("timer fired once");
done = true;
}
_ = sleep(Duration::from_millis(40)) => {
rounds += 1;
println!("round {rounds}");
}
}
}
}Without if !done, the second poll of a finished Sleep would be a bug. Note that the precondition is evaluated each time, but the branch future expression is still only evaluated when the branch is enabled.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Deadline never fires in a busy loop | `sleep(...)` created inside `select!` | Create it before the loop, pin it, poll `&mut` |
| Compile error that `Sleep` cannot be unpinned | Passing `&mut` to an unpinned future | Use `tokio::pin!` or `Box::pin` |
| Panic: all branches disabled | Every pattern failed or precondition was false, and no `else` | Add an `else` branch |
| Panic from polling a finished future | Reusing a completed pinned future | Add an `if` precondition or reset it |
Exercise
A loop uses select! with rx.recv() and sleep(Duration::from_secs(5)) written directly inside the macro. Messages arrive every second. Will the five-second timeout ever fire, and how do you change the code so it fires five seconds after the loop starts?
Show answer
It never fires, because each iteration drops the old sleep and creates a new one, restarting the five seconds. Create let deadline = sleep(Duration::from_secs(5)); tokio::pin!(deadline); before the loop and use _ = &mut deadline in the select!.