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
- fetch wins: a quicker fetch finishes first. Its branch runs, and the timer is dropped instead.
- a spawned task:
fetchruns as its own task. The timer wins, but dropping theJoinHandledoesn’t stop the task:fetch endsstill prints.
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