Sub topic 15
Cancellation happens at await points when a future is dropped
This chapter assumes you have read the earlier chapters on Future, poll, wakers, and Pin. You should know that an async fn compiles to a state machine and that an executor drives it by calling poll. Here you will see what happens when nobody polls a future again.
Cancelling means dropping
Rust has no cancel method on futures. A future is a plain value, and the way to cancel it is to drop it. The future's Drop glue runs, and the future is never polled again. Any code after its current suspension point never runs.
This happens in ordinary situations:
- A
select-style combinator finishes when one branch completes and drops the other branches. - A timeout wrapper drops the inner future when the deadline passes.
- A caller drops a future it no longer needs, or a task is aborted.
- An error returned with
?from a parent future drops sibling futures that were still running.
Why it happens at await points
A future only runs while someone is inside poll. Between polls it is just data, parked at the last .await that returned Poll::Pending. A drop can only arrive between polls, so the future can only be stopped at one of those suspension points. It can never be stopped in the middle of a synchronous stretch of code.
The compiler-generated state machine records which suspension point it is parked at. Dropping it drops exactly the locals that are alive at that point. Locals declared after the await were never created, so they are never dropped.
Observing a drop
This program polls a future once, then drops it while it is suspended. It uses only the standard library. YieldOnce is a hand-written future that returns Pending once and wakes itself, like the CountDown future from the earlier chapter.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
struct NoopWake;
impl Wake for NoopWake {
fn wake(self: Arc<Self>) {}
}
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
async fn job() {
let _a = Noisy("before await");
println!("step 1");
YieldOnce(false).await;
let _b = Noisy("after await");
println!("step 2");
}
async fn forward_lossy(queue: &mut Vec<u32>, sink: &mut Vec<u32>) {
while let Some(item) = queue.pop() {
YieldOnce(false).await;
sink.push(item);
}
}
async fn forward_safe(queue: &mut Vec<u32>, sink: &mut Vec<u32>) {
while let Some(&item) = queue.last() {
YieldOnce(false).await;
queue.pop();
sink.push(item);
}
}
fn poll_once_then_drop<F: Future>(fut: F) {
let waker = Waker::from(Arc::new(NoopWake));
let mut cx = Context::from_waker(&waker);
let mut fut = Box::pin(fut);
println!("pending: {}", fut.as_mut().poll(&mut cx).is_pending());
drop(fut);
println!("dropped");
}
fn main() {
poll_once_then_drop(job());
let mut queue = vec![1, 2, 3];
let mut sink = Vec::new();
poll_once_then_drop(forward_lossy(&mut queue, &mut sink));
println!("lossy: queue={:?} sink={:?}", queue, sink);
let mut queue = vec![1, 2, 3];
let mut sink = Vec::new();
poll_once_then_drop(forward_safe(&mut queue, &mut sink));
println!("safe: queue={:?} sink={:?}", queue, sink);
}The first call prints:
step 1
pending: true
drop before await
dropped"step 2" never prints, and _b is never created. Only _a was alive when the future was suspended, so only _a is dropped.
Cancel safety and lost work
The second and third calls show the real hazard. forward_lossy removes 3 from queue and then awaits before pushing it to sink. Cancelling it at that await loses the item:
pending: true
dropped
lossy: queue=[1, 2] sink=[]forward_safe only looks at the item with last(). It removes it from the queue and pushes it to the sink with no await between the two steps. Cancelling leaves the data intact:
pending: true
dropped
safe: queue=[1, 2, 3] sink=[]A future is cancel safe if dropping it at any await point leaves your data consistent and loses nothing you cannot recover. Cancel safety is a property you design for. The compiler does not check it.
Some practical rules follow:
- Avoid holding data that has been removed from shared state across an await. Peek first and commit after the await, or make the removal and the use happen in one synchronous step.
- Treat a sequence of steps that must all happen together as not cancel safe unless you protect it. Examples are "debit account, await, credit account" and "write header, await, write body".
- Read library documentation for a "cancel safety" note before putting an operation in a
selectbranch. For example, a read that may have consumed bytes into an internal buffer behaves differently from one that only waits for readiness. - If you need an operation to finish regardless of the caller, spawn it as a task (see below) and await its result.
Cleanup must be synchronous
Rust has no async Drop. The drop that runs on cancellation is an ordinary synchronous function, and it cannot .await. A guard can release a lock, close a file handle, or decrement a counter, because those are synchronous. It cannot flush a network connection gracefully, because that needs I/O that may itself be pending.
Common workarounds:
- Give the type an explicit
async fn close(self)and call it on the normal path. UseDropas a best-effort fallback for the cancelled path. - Have
Dropsend a message on a channel to a background task that performs the async cleanup.
Dropping a spawned task is different
Everything above concerns a future you own directly. A spawned task is owned by the runtime. In Tokio, dropping the JoinHandle detaches the task, and the task keeps running. To cancel it you call an explicit method such as abort, and the runtime then drops the task's future at its next suspension point. The same await-point rule applies. Dropping a handle you never joined is a common cause of work that unexpectedly continues in the background.
Summary of behaviors
| Situation | What happens to the future |
|---|---|
| Dropped before its first poll | None of the body runs. Captured arguments are dropped. |
| Dropped while suspended at an await | Locals alive at that await are dropped. Later code never runs. |
| Dropped after returning `Ready` | Nothing extra happens. It was already complete. |
| Losing branch of a `select` | Dropped immediately after the winner completes. |
| `JoinHandle` of a spawned task dropped | The task is detached and keeps running. |
Exercise
In the program above, change job so that let _b = Noisy("after await"); comes before YieldOnce(false).await; and keep everything else the same. What does poll_once_then_drop(job()) print, and why?
Show answer
It prints "step 1", "pending: true", then "drop after await" and "drop before await" in that order, then "dropped". Both guards are alive when the future is suspended, so dropping the future drops both. Locals are dropped in reverse declaration order, so _b is dropped before _a. The string "step 2" still never prints, because the code after the await never runs.