tokio::select!: the first branch wins, the others are dropped

Read the explanation
What if

select! races fetch against a 50 ms timer on main's task. The timer wins, so fetch is dropped mid-await and fetch ends never prints.

Predict first

The 50 ms timer wins the select!, and main then waits another 100 ms. Does fetch print fetch ends?

0123456789tokio::select!main: print timed outprintsleep(100 ms).awaitprint donefetch: fetch startsstartssleep(100 ms).awaitdropped: fetch ends never runssleep(50 ms)

Tap any block to see what that thread is doing.

  • Waiting / parked
  • Running
  • Waiting on I/O
  • Skipped
Step 1/5

select! polls both branches on main's own task: fetch starts, and so does the 50 ms timer.

1async fn fetch() -> &'static str {2    println!("fetch starts");3    sleep(Duration::from_millis(100)).await; // a slow network call4    println!("fetch ends"); // runs only if fetch wins5    "data"6}7 8#[tokio::main]9async fn main() {10    tokio::select! {11        data = fetch() => println!("got {data}"),12        _ = sleep(Duration::from_millis(50)) => println!("timed out"),13    } // the losing branch is dropped here14    sleep(Duration::from_millis(100)).await; // fetch would have ended by now15    println!("done");16}

Explanation

What just happened

select! started both branches on main’s task and waited for the first to finish. The 50 ms timer won, so select! ran its branch and dropped fetch in the middle of its sleep. fetch ends never printed, not even 100 ms later.

Try the what-if switch

Why

A future only makes progress when something polls it. select! stops polling the losers and drops them, so they end at whatever .await they were waiting on. A spawned task is polled by the runtime, not by you, so dropping its handle leaves it running.

When to use it

Timeouts, “whichever answers first”, or stopping work when a shutdown signal arrives. To wait for all of them instead, use join!.

Watch out

A branch dropped halfway through something, like a partly read message, loses that work. And to stop a spawned task, call abort() on its handle.

Common questions

What happens to the branch that loses select!?

It is dropped. A dropped future is never polled again, so the code after its pending .await never runs, and anything it owned is dropped before the code after select! runs.

Does select! cancel a spawned task?

No. A branch that awaits a JoinHandle only drops the handle, and the task keeps running to the end. Call abort() on the handle to stop it.

Does select! run its branches on several threads?

No. Like join!, it polls every branch on the calling task's thread, and they take turns at their .awaits.

Verified: this timeline matches a real program, checked in CI on Rust 1.99 with Tokio 1.54. How we verify. Unclear or wrong? Tell us