Sub topic 14
Cancellation by dropping futures
This chapter assumes you can write async fn, use .await, and run a Tokio program. You should also know what Drop does and how tokio::spawn, join!, and select! are used. Here you will learn what cancellation is in async Rust, what runs when it happens, and how to write code that survives it.
Cancellation is dropping
A future does nothing unless something polls it. Rust has no cancel call for plain futures. To cancel one, you stop polling it and drop it. The future's state machine is destroyed, and every local variable that is alive at its current .await point is dropped in the usual order. Code after that .await never runs.
Cancellation can only happen at an .await point, and only when the future returned Pending there. The future is not running while it waits, so the dropping code has exclusive access to it.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
async fn slow_job() {
let _guard = Guard("job");
println!("start");
sleep(Duration::from_secs(5)).await;
println!("never printed");
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(100), slow_job()).await;
println!("timed out: {}", result.is_err());
}The output is start, drop job, then timed out: true. The line after the sleep never runs, but the guard's destructor does.
Where cancellation comes from
Several common tools cancel futures for you:
| Tool | What gets dropped |
|---|---|
| `tokio::time::timeout` | The inner future, when the deadline passes |
| `tokio::select!` | Every branch future that did not win |
| `JoinHandle::abort` | The spawned task's future, at its next `.await` |
| Dropping a future you never finished awaiting | That future |
| Runtime shutdown | All tasks that are still running |
Two points are easy to get wrong:
- Dropping a
JoinHandledoes not cancel the task. It detaches the handle, and the task keeps running. Callabort()to cancel it. - With
join!, a future is dropped only if the wholejoin!future is dropped. Withselect!, losing branches are dropped as soon as one branch wins.
Cancelling a spawned task
abort() asks the runtime to drop the task's future the next time the task yields. Awaiting the handle afterwards gives you a JoinError, and is_cancelled() tells you why the task ended.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_secs(5)).await;
42
});
sleep(Duration::from_millis(50)).await;
handle.abort();
match handle.await {
Ok(v) => println!("value {v}"),
Err(e) if e.is_cancelled() => println!("cancelled"),
Err(e) => println!("panicked: {e}"),
}
}This prints cancelled. If the task had already finished when you called abort(), awaiting the handle returns Ok. Always handle both outcomes.
A task can only be cancelled where it awaits. A loop that never awaits, such as a long calculation, ignores abort() until it reaches an .await. This is the same reason blocking code harms a runtime.
Cancel safety
A future is cancel safe if dropping it at an .await point loses no data and leaves nothing half done. The Tokio docs mark each method as cancel safe or not. mpsc::Receiver::recv is cancel safe: if it is dropped while waiting, no message is consumed. Your own async fn is not automatically cancel safe.
The usual problem is a function that does several awaits in a row and holds partial progress in local variables. Cancellation throws that progress away.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
async fn recv_pair(rx: &mut mpsc::Receiver<u32>) -> Option<(u32, u32)> {
let a = rx.recv().await?;
let b = rx.recv().await?;
Some((a, b))
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tx.send(1).await.unwrap();
let tx2 = tx.clone();
tokio::spawn(async move {
sleep(Duration::from_millis(200)).await;
tx2.send(2).await.unwrap();
tx2.send(3).await.unwrap();
});
tokio::select! {
pair = recv_pair(&mut rx) => println!("pair {pair:?}"),
_ = sleep(Duration::from_millis(100)) => println!("tick"),
}
println!("next: {:?}", rx.recv().await);
}The output is tick then next: Some(2). The value 1 was received into the local a. The 100 ms timer won, so recv_pair was dropped and a was lost. The program never reports an error, and one message has silently disappeared.
You can fix this in three ways:
- Keep the partial state outside the future. Pass
&mut Option<u32>intorecv_pairand storeathere before the second await. A retry then resumes where it stopped. - Make the cancelled part a single cancel-safe operation, and combine results after
select!finishes. - Spawn the multi-step work as its own task and have
select!wait on itsJoinHandle. Dropping a handle does not cancel the task, so the work completes.
In a select! inside a loop, create the long-lived future once, pin it, and pass &mut fut to select!. Otherwise every iteration builds a new future and discards the old one's progress.
Cleanup when you are dropped
Drop::drop is a plain synchronous function. You cannot .await inside it. Cleanup that must happen on cancellation therefore has to be one of these:
- Synchronous work, such as releasing a lock, removing a temp file with
std::fs, or sending on an unbounded channel withsend. - A new task started from
dropwithtokio::spawn. This only works while a runtime is still running, and it is not guaranteed to finish.
Async cleanup that must always run is better handled with an explicit shutdown step. For example, signal the task with a cancellation message or channel, let it finish its cleanup, and await its JoinHandle. abort() should be reserved for work that is safe to cut off.
Common errors
- Assuming code after an
.awaitalways runs. If a caller can drop your future, a step that must happen, such as committing or acknowledging, needs a drop guard or a design that tolerates being stopped. - Using a non-cancel-safe future as a
select!branch. Check the documentation of each method you put there. - Expecting
drop(handle)to stop a task. It only detaches it. - Holding a
std::sync::MutexGuardor other state across an.awaitin a future that may be cancelled. Dropping releases it, but the data the guard protected may be left half updated. - Treating a
JoinErroras always a panic. Checkis_cancelled()first.
Exercise
A task is started with let h = tokio::spawn(work());. Later the code runs drop(h); and then the program continues. Is work() cancelled? What call would cancel it, and what does awaiting the handle return afterwards?
Show answer
No. Dropping a JoinHandle detaches the task, and it keeps running. h.abort() cancels it, and the task's future is dropped at its next .await. Awaiting the handle then returns Err(JoinError) where is_cancelled() is true. If the task had already finished, the await returns Ok with its output.
Exercise
In select! inside a loop, one branch calls read_frame(&mut socket), an async fn that reads a 4-byte length with one await and then the body with another. A second branch fires a periodic timer. Why can this corrupt the stream, and how would you fix it?
Show answer
When the timer branch wins, read_frame is dropped. If it had already read the length, that value and the bytes it consumed are lost, so the next call starts in the middle of a frame. To fix it, store the partial frame state outside the future and resume it on the next call. Alternatively, run the reader in its own spawned task that sends complete frames over a channel, and select! on rx.recv(), which is cancel safe.