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. It also assumes you can read async/await code and use tokio::spawn and mpsc channels. Here you will see what changes when select! runs inside a loop.
Every pass through the loop starts a new select!
A select! invocation is a one-shot race. Each time the loop reaches it, Tokio evaluates every branch expression, polls the resulting futures until one completes, and drops the losers. On the next iteration it evaluates the expressions again.
This is harmless for rx.recv(). A new recv() future starts from the same place as the dropped one, because recv is cancel safe. It matters for futures that hold progress, such as a 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..3 {
let _ = tx.send(i).await;
sleep(Duration::from_millis(40)).await;
}
});
loop {
tokio::select! {
Some(n) = rx.recv() => println!("got {n}"),
_ = sleep(Duration::from_millis(100)) => {
println!("idle for 100 ms");
break;
}
}
}
}Each message wins the race, so the sleep future is dropped and a new 100 ms timer starts on the next pass. The timer therefore measures idle time, the gap since the last message. That is a reasonable meaning. It is not an overall deadline, which is what people often intend. If messages arrive every 40 ms forever, this loop never times out.
Keeping one deadline: pin outside the loop
To keep a single deadline, create the future once, before the loop, and poll it by mutable reference inside select!.
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;
}
}
}
}Two details make this work.
- Dropping a reference does not drop the future. When the
recvbranch wins,select!drops the&mut deadlineborrow. TheSleepfuture itself stays alive inmain, and its timer keeps running. &mut Fis a future only ifF: Unpin.Sleepis notUnpin, sotokio::pin!pins it on the stack and rebindsdeadlineas aPin<&mut Sleep>. A pinned mutable reference isUnpin, so&mut deadlineis accepted. Without the pin you get a compile error saying the future cannot be unpinned.
Async blocks and the futures returned by async fn are also !Unpin. You must pin them the same way before polling them by reference.
The table summarizes where a future is created and what that means in a loop.
| Written in the branch | Created | When it loses the race | Next iteration |
|---|---|---|---|
| `sleep(d)` | every iteration | dropped | new timer starts from zero |
| `rx.recv()` | every iteration | dropped, nothing lost (cancel safe) | new `recv` future, same channel state |
| `tick.tick()` with `interval` made before the loop | the interval once, the tick future every iteration | dropped, cancel safe | next tick on the original schedule |
| `&mut pinned` | once, before the loop | not dropped, keeps its state | resumes where it stopped |
Create interval before the loop, as in the earlier chapters. If you wrote interval(d).tick() inside the branch, you would get a fresh interval each time, and its first tick completes immediately.
Resuming a long operation that is not cancel safe
The same technique fixes a cancel-safety problem. If an operation has several await points and keeps partial progress in its own state, dropping it loses that progress. Pinning it outside the loop and polling it by &mut means other branches can win without cancelling it.
use std::time::Duration;
use tokio::{sync::mpsc, time::sleep};
async fn slow_job() -> String {
println!("job: step 1");
sleep(Duration::from_millis(100)).await;
println!("job: step 2");
sleep(Duration::from_millis(100)).await;
"job result".to_string()
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
for i in 0..4 {
let _ = tx.send(i).await;
sleep(Duration::from_millis(60)).await;
}
});
let job = slow_job();
tokio::pin!(job);
let mut job_done = false;
loop {
tokio::select! {
res = &mut job, if !job_done => {
println!("finished: {res}");
job_done = true;
}
Some(n) = rx.recv() => println!("got {n}"),
else => break,
}
}
}Each message interrupts the race, but job is never restarted. "job: step 1" and "job: step 2" each print once. If you wrote res = slow_job() in the branch, every incoming message would drop the job and the next iteration would start it again, so it would probably never finish.
Remember that a future created by slow_job() does nothing until first polled. The job begins on the first pass through select!, not at the let job = ... line.
Disabled branches
The example above uses two ways to disable a branch. Both only affect the current select! invocation, and both exist to stop the loop from misbehaving.
Preconditions with `if`
A branch can carry a guard: pattern = future, if condition => handler. When the condition is false, the future is not polled and the branch cannot win. The future expression is still evaluated, so it must be safe to construct even when it will not be polled. In the example, &mut job only borrows, so that is fine.
The guard is needed because polling a completed future is a bug. An async fn future panics if polled after it returns Ready. After the job finishes, the loop keeps running to process messages, so the job branch must be switched off with if !job_done.
Patterns that fail to match
If a branch has a refutable pattern such as Some(n) and the future's output does not match, that branch is disabled for the rest of this select! call. Other branches continue to be polled. In the deadline example, when the sender finishes, rx.recv() returns None, which does not match Some(n). The recv branch drops out and the select! waits for deadline. On the next iteration recv() returns None again immediately, so the branch is disabled again.
The `else` branch and the all-disabled panic
If every branch is disabled, select! runs the else branch if there is one. With no else, it panics with a message that all branches are disabled. In slow_job above, once the job is done and the channel is closed, both branches are disabled, so else => break ends the loop cleanly.
Fairness and `biased;`
By default select! picks a random starting branch on each call, so a busy branch cannot starve the others. Starting a select! body with biased; makes it poll branches from top to bottom instead. This is useful in loops where one branch must take priority, such as a shutdown signal placed first. The cost is starvation. If an earlier branch is always ready, later branches never run.
Common mistakes
- Creating a timer in the branch and expecting a deadline. You get an idle timeout. Pin the timer before the loop for a deadline.
- Pinning without a done flag. The loop panics on the first iteration after the future completes.
- Passing a
!Unpinfuture by&mutwithout pinning. The compiler rejects it. Usetokio::pin!, orBox::pinif the future must be moved. - Using
ifto skip work. The branch expression still runs, so side effects inside it still happen. - Relying on a refutable pattern in a loop that must continue. A closed channel disables the branch but does not end the loop. Add an
elsebranch or handleNoneexplicitly, as in the first channel example in this series.
Exercise
A loop selects on rx.recv() and on sleep(Duration::from_secs(5)), with the sleep written directly in its branch. The channel delivers a message every second. Will the "5 seconds passed" handler ever run? How would you make it fire five seconds after the loop starts?
Show answer
It never runs. Each message makes the recv branch win, the sleep future is dropped, and the next iteration creates a new 5-second timer. Create the sleep before the loop, call tokio::pin! on it, and use _ = &mut deadline in the branch. Then one timer runs for the whole loop.
Exercise
In the slow_job example, why does the job branch need if !job_done, and what happens if you remove it?
Show answer
After &mut job returns its result, the async fn future is finished. The loop continues because the channel may still have messages, so the next select! would poll the finished future again, which panics. The guard disables that branch once the result has been handled.