Sub topic 13
Cancellation by dropping futures
This chapter assumes you know ownership and Drop, can write async fn and .await, and have used tokio::spawn, timeout, and select!. Here you will learn how a future is cancelled, what that means for your code, and how to write code that survives it.
Cancellation is just drop
A future is a value. Rust has no separate "cancel" call. To cancel a future, you drop it. Once it is dropped, nobody polls it again, and its local variables are dropped too.
A future can only be dropped at a point where it is not running. For an async function, that means an .await point. Code between two .await points always runs to completion.
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 slow() {
let _guard = Noisy("guard");
println!("started");
sleep(Duration::from_secs(5)).await;
println!("never printed");
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(100), slow()).await;
println!("timed out: {}", result.is_err());
}The output is started, dropping guard, then timed out: true. The line "never printed" does not appear, because the future was dropped while it waited on sleep.
Where cancellation comes from
Several tools cancel futures for you:
| Tool | What gets dropped |
|---|---|
| `timeout` | The inner future, when the deadline passes |
| `select!` | Every branch that did not finish first |
| `JoinHandle::abort` | The spawned task's future, at its next `.await` |
| Dropping a `JoinHandle` | Nothing. The task keeps running, detached |
The last row surprises many people. Dropping a JoinHandle does not cancel the task. Only abort does.
Cancel safety
A future is cancel safe if dropping it at any .await loses no data and leaves no half-finished work. Consider this loop:
use tokio::io::{AsyncRead, AsyncReadExt};
async fn read_two<R: AsyncRead + Unpin>(r: &mut R) -> std::io::Result<[u8; 8]> {
let mut buf = [0u8; 8];
r.read_exact(&mut buf[..4]).await?;
r.read_exact(&mut buf[4..]).await?;
Ok(buf)
}If this future is dropped between the two reads, the first 4 bytes are gone. The next caller starts reading from the middle of the message. Putting read_two in a select! branch can therefore corrupt a stream.
Some Tokio methods document that they are cancel safe. mpsc::Receiver::recv is one: if it is dropped before it returns, no message is lost. Check each method's documentation before using it in select!.
Writing code that survives cancellation
- Keep state outside the future. If you re-create the future each loop turn, keep partial data in a variable that lives across turns.
- Use
Dropfor cleanup. Locks, files, and guards are released when the future is dropped. - Do not rely on code after an
.awaitto run. Cleanup that must happen belongs in aDropimplementation. - Create a future once and pass
&muttoselect!if you want to keep it alive across loop turns. The future must be pinned, for example withtokio::pin!.
Exercise
A task is started with let h = tokio::spawn(work());. Then h goes out of scope without abort or .await. Is work() cancelled?
Show answer
No. Dropping a JoinHandle detaches the task, and it keeps running. Only calling h.abort() (or shutting down the runtime) cancels it.
Exercise
In a select! with two branches, branch 2 finishes first. What happens to the future in branch 1, and what must its code handle?
Show answer
Branch 1's future is dropped at its current .await. Its locals are dropped, and any work after that .await never runs. The code must be cancel safe, so that no data is lost or left half done.