Sub topic 15
Cancellation happens at await points when a future is dropped
This chapter assumes you know how poll and Poll::Pending work, what an async fn compiles to (a state machine), and how Rust's Drop runs destructors.
Cancelling means dropping
Rust has no cancel method on futures. To cancel a future, you stop polling it and drop it. Because an async fn is a state machine, dropping it drops whatever the machine holds in its current state. That means every local variable that is live at the last .await it reached.
Code before that .await has already run. Code after it never runs.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
struct Never;
impl Future for Never {
type Output = ();
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
Poll::Pending
}
}
async fn work() {
let _guard = Guard("guard");
println!("step 1");
Never.await;
println!("step 2");
}
fn main() {
let mut cx = Context::from_waker(Waker::noop());
let mut fut = Box::pin(work());
println!("{:?}", fut.as_mut().poll(&mut cx));
drop(fut);
println!("dropped future");
}This needs Rust 1.85 or later for Waker::noop. It prints:
step 1
Pending
drop guard
dropped futureThe first poll ran up to Never.await and returned Pending. Dropping the future then ran Guard::drop. "step 2" never printed.
Where cancellation happens
A future can only be dropped while it is not being polled. For an async body, that means it can only be cancelled at an .await that returned Pending. Code between two awaits always runs to completion, because nothing else can interrupt it.
Common ways a future gets dropped:
- A
select-style combinator finishes when one branch completes and drops the others. - A timeout wrapper drops the inner future when time runs out.
- A task handle aborts its task.
- You drop a future without ever awaiting it.
Futures are lazy, so a future you never poll never runs at all.
Writing cancellation-safe code
Cleanup that lives in Drop impls runs on cancellation. Cleanup written as plain statements after an .await does not.
The bigger risk is partial work. Suppose a function reads a message from a buffer, then awaits a write. If the future is dropped at that await, the message is already removed and was never sent. Two habits help:
- Keep state changes and the awaits that depend on them close together, or make the change only after the await succeeds.
- Put required cleanup in a guard type with a
Dropimpl.
Drop is synchronous. You cannot .await inside it, so async cleanup must be done another way, such as an explicit shutdown call before the value goes away.
Exercise
In work() above, move println!("step 1"); after Never.await;. What does the program print, and why?
Show answer
It prints Pending, then drop guard, then dropped future. The first poll suspends at Never.await before reaching the println!. The future is then dropped, so the statement never runs. The guard is still dropped, because it was created before the await.