Sub topic 3
Cancellation means dropping the future
This chapter assumes you know basic Rust (ownership, borrowing, the Drop trait), async/await syntax, and how to start a Tokio runtime with #[tokio::main] and tokio::spawn.
The working model
Rust has no "cancel" call for futures. A future is a value, and you cancel it by dropping it. When a future is dropped, Rust drops every local variable that the future was holding at its current suspension point. The future is never polled again, so nothing after that point runs.
This follows from two earlier facts. A future does nothing until it is polled. A future can only pause at an .await. So a dropped future simply stops where it last paused.
What happens to state
An async fn compiles into a state machine. Each .await is a state, and the locals that are alive at that await are stored inside the future. Dropping the future drops those locals in the usual order.
The next example shows this. timeout wraps work() and drops it after 50 milliseconds.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
async fn work() {
let _guard = Noisy("work state");
sleep(Duration::from_secs(10)).await;
println!("never printed");
}
#[tokio::main]
async fn main() {
let _ = timeout(Duration::from_millis(50), work()).await;
println!("after timeout");
}The output is:
dropping work state
after timeout_guard is dropped because it was alive at the sleep await. The line never printed is skipped because the code after the await never gets another poll.
Cancellation is silent to the future
The future gets no notice and no chance to return an error. Only destructors run. This has three consequences.
- Code between two awaits always runs to completion. Cancellation cannot interrupt it.
- Code after an await may never run. Any step you need to happen, such as releasing a lock in a protocol or sending a final message, cannot rely on being reached.
- Cleanup belongs in
Dropimplementations, not in the straight-line code after an await.
Who drops a future
Several tools cancel by dropping:
| Tool | When the future is dropped |
|---|---|
| `tokio::time::timeout` | The deadline passes before the inner future finishes |
| `tokio::select!` | Another branch completes first, so the losing futures are dropped |
| Dropping the value yourself | You call `drop(fut)` or let it go out of scope unpolled or half-polled |
| Parent future dropped | A future that contains other futures drops them too |
The last row matters. Dropping an outer future drops everything nested inside it, so cancellation spreads down the whole chain of awaits.
A spawned task is different
tokio::spawn hands the future to the runtime. Dropping the JoinHandle does not drop the task. It only detaches it, and the task keeps running. To stop a spawned task you must call abort() or signal it. Later chapters cover both.
Common errors
- Assuming cleanup code runs. Writing
release();after an await and expecting it to run on timeout. Use a guard type withDrop. - Forgetting that partial work is lost. If a future has read half a message into a local buffer when it is dropped, that buffer is gone. Whether this is safe depends on the operation, and the cancel safety chapter covers it.
- Expecting cancellation inside blocking code. A future that never reaches an await cannot be dropped partway, because the caller never regains control.
Exercise
A function awaits sleep(10s), then calls println!("finished"). You wrap it in timeout(1s, ...). What happens to the println!, and what happens to locals that were alive at the sleep?
Show answer
The println! never runs, because the timeout drops the future while it is paused at the sleep and the future is never polled again. The locals alive at the sleep are dropped, so their Drop implementations run.