Sub topic 14
Cancellation and cancel safety
This chapter assumes you know how to spawn tasks, use tokio::select!, and read a JoinHandle. It explains what happens to a future when it is dropped, and how to write code that survives it.
Cancellation is dropping
A future in Rust does nothing until it is polled. The reverse is also true: when a future is dropped, it stops. Nothing after its current .await point runs, and its local variables are dropped in order. This is cancellation.
You trigger it in a few common ways:
tokio::select!drops every branch that did not finish first.tokio::time::timeoutdrops the inner future when the deadline passes.JoinHandle::abort()asks the runtime to drop a spawned task at its next.await.- Dropping a plain future you never awaited.
Dropping a JoinHandle does not cancel the task. It only detaches it.
Seeing a drop happen
Code after an .await can be skipped. Cleanup that lives only in straight-line code may never run.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("dropped {}", self.0);
}
}
async fn work() {
let _guard = Guard("work guard");
println!("started");
sleep(Duration::from_secs(5)).await;
println!("finished");
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(100), work()).await;
println!("timed out: {}", result.is_err());
}The output is started, dropped work guard, then timed out: true. The line finished never prints. The Drop implementation is the reliable place for cleanup, because it runs whether the future completes or is cancelled.
What cancel safety means
A future is cancel safe if dropping it at an .await point loses no data and leaves no half-finished state. This matters most in select! inside a loop, where a branch is dropped and recreated on each iteration.
Some examples:
mpsc::Receiver::recvis cancel safe. If it is dropped, no message is taken from the channel.sleepis cancel safe. It holds no data.AsyncWriteExt::write_allis not. If it is dropped midway, some bytes may have been written and you can't tell how many.AsyncReadExt::read_exactis not. Bytes already read into the buffer are lost to you.
The Tokio documentation states the cancel safety of each method that is used with select!. Check it before you put a method in a branch.
Fixing a cancel-unsafe branch
Create the unsafe future once, outside the loop, and pass it by mutable reference. It then keeps its progress between iterations.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
async fn slow_job() -> &'static str {
sleep(Duration::from_millis(250)).await;
"job done"
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
tokio::spawn(async move {
for i in 0..3 {
tx.send(i).await.unwrap();
sleep(Duration::from_millis(50)).await;
}
});
let job = slow_job();
tokio::pin!(job);
loop {
tokio::select! {
Some(n) = rx.recv() => println!("message {n}"),
result = &mut job => {
println!("{result}");
break;
}
}
}
}If slow_job() were written inside the select!, each message would restart the job and discard its progress. Here tokio::pin! fixes the future in place so &mut job can be polled repeatedly.
Aborting a task
handle.abort() cancels a spawned task at its next .await. Awaiting the handle afterwards returns Err, and JoinError::is_cancelled() is true. A task in a long loop with no .await can't be aborted until it yields.
Exercise
A loop uses tokio::select! with one branch that calls reader.read_exact(&mut buf) and another that waits on a shutdown signal. Why is this risky, and how would you fix it?
Show answer
read_exact is not cancel safe. If the shutdown branch wins, or a loop iteration drops the read, bytes already read into buf are lost. Fix it by creating the read future outside the loop and polling it by &mut after tokio::pin!, or by moving the read into its own task that sends complete messages over a channel, and having select! wait on that cancel safe recv.