Sub topic 14
Cancellation and cancel safety
This chapter assumes you can spawn tasks, use select!, and read JoinHandle results. These are covered in the earlier chapters on tasks and on join!/select!. Here you will learn what happens to a future that never finishes, and how to write code that survives it.
What cancellation means in async Rust
A future is a value, and a future that is dropped before it completes is cancelled. Nothing else happens. There is no exception and no signal. The runtime stops polling the future and runs the destructors of everything the future holds at its current .await point.
Two consequences follow:
- A future can only be cancelled at an
.await. Between two awaits, the code runs to completion. - Code after the
.awaitwhere the future was dropped never runs.
The next program shows this. A Guard prints when it is dropped, and timeout drops the slow future after 100 ms.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
async fn slow() -> u32 {
let _g = Guard("slow");
println!("slow: started");
sleep(Duration::from_secs(5)).await;
println!("slow: finished");
42
}
#[tokio::main]
async fn main() {
let result = timeout(Duration::from_millis(100), slow()).await;
println!("timed out: {}", result.is_err());
}The output is slow: started, dropping slow, then timed out: true. The line slow: finished never prints.
Where cancellation comes from
| Source | What gets dropped |
|---|---|
| `tokio::select!` | Every branch future that did not win |
| `tokio::time::timeout` | The inner future when the deadline passes |
| `JoinHandle::abort()` | The task's future, at its next yield point |
| Runtime shutdown | All tasks still alive when the runtime is dropped |
| Early `return` or `?` | Any future you were holding but had not finished |
Dropping a JoinHandle does not cancel its task. The task is detached and keeps running. Cancelling a task requires abort() or a cooperative signal such as a channel or a CancellationToken from the tokio-util crate.
Aborting a task
abort() asks the runtime to cancel a spawned task. Awaiting the handle afterwards returns a JoinError that reports the cancellation.
use std::time::Duration;
use tokio::time::sleep;
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
let _g = Guard("task");
sleep(Duration::from_secs(10)).await;
});
sleep(Duration::from_millis(50)).await;
handle.abort();
let err = handle.await.unwrap_err();
println!("cancelled: {}", err.is_cancelled());
}If the task had already finished before abort() ran, awaiting the handle returns Ok with the task's value. Always check is_cancelled() before treating a JoinError as a panic.
Cancel safety
An operation is cancel safe if dropping its future before completion loses no data and leaves no half-finished state. You can then retry in a loop without worrying about which branch of select! won. If an operation is not cancel safe, dropping it midway can lose data or leave things half-done.
The Tokio documentation has a "Cancel safety" section for each method. The table shows common cases.
| Operation | Cancel safe? | Reason |
|---|---|---|
| `mpsc::Receiver::recv` | Yes | A message is removed only when `recv` returns it |
| `TcpListener::accept` | Yes | A connection is taken only on completion |
| `sleep`, `Interval::tick` | Yes | No data involved |
| `AsyncReadExt::read` | Yes | If it was dropped, no bytes were read |
| `AsyncReadExt::read_exact` | No | Bytes already read into the buffer are lost track of |
| `AsyncWriteExt::write_all` | No | An unknown prefix may already be written |
| `mpsc::Sender::send` | Partly | The message is dropped on cancel. `reserve` avoids this |
Cancel safety is a property of the future, so it also applies to your own async fn. Your function is cancel safe only if every await point can be abandoned without losing something.
A lossy async function
recv_pair below reads two values from a channel. If the future is dropped after the first recv but before the second, the first value is gone.
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();
tokio::select! {
pair = recv_pair(&mut rx) => println!("pair: {pair:?}"),
_ = sleep(Duration::from_millis(50)) => println!("timeout"),
}
tx.send(2).await.unwrap();
drop(tx);
println!("next: {:?}", rx.recv().await);
}The output is timeout and then next: Some(2). The value 1 was received by the dropped future and discarded with it.
Fix 1: keep progress outside the future
Move the partial state into a variable owned by the caller. A cancelled call then leaves its progress behind.
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::sleep;
async fn recv_pair(
rx: &mut mpsc::Receiver<u32>,
first: &mut Option<u32>,
) -> Option<(u32, u32)> {
if first.is_none() {
*first = Some(rx.recv().await?);
}
let b = rx.recv().await?;
Some((first.take().unwrap(), b))
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<u32>(8);
let mut first = None;
tx.send(1).await.unwrap();
tokio::select! {
pair = recv_pair(&mut rx, &mut first) => println!("pair: {pair:?}"),
_ = sleep(Duration::from_millis(50)) => println!("timeout"),
}
tx.send(2).await.unwrap();
println!("pair: {:?}", recv_pair(&mut rx, &mut first).await);
}The second call prints pair: Some((1, 2)), so nothing was lost.
Fix 2: do not recreate the future
In a select! loop, an expression such as reader.read_exact(&mut buf) creates a new future on every iteration. Instead, create the future once, pin it, and select on &mut of it. The future then survives the other branches winning.
use tokio::io::{duplex, AsyncReadExt, AsyncWriteExt};
use tokio::time::{interval, sleep, Duration};
#[tokio::main]
async fn main() {
let (mut client, mut server) = duplex(64);
tokio::spawn(async move {
client.write_all(b"he").await.unwrap();
sleep(Duration::from_millis(120)).await;
client.write_all(b"llo").await.unwrap();
});
let mut buf = [0u8; 5];
let mut ticker = interval(Duration::from_millis(50));
{
let read = server.read_exact(&mut buf);
tokio::pin!(read);
loop {
tokio::select! {
res = &mut read => {
res.unwrap();
break;
}
_ = ticker.tick() => println!("tick"),
}
}
}
println!("{}", String::from_utf8_lossy(&buf));
}Several ticks print while the data arrives in two pieces, then hello. Without the pin, each tick would drop the partly completed read_exact and the two bytes he would be lost.
A third option is to avoid the problem by structure. Give each source its own task and communicate over channels, so no select! has to drop a lossy future.
Cleanup when a future is dropped
Drop is synchronous, so you cannot .await inside it. Use drop guards for work that can be done without waiting: releasing a counter, removing an entry from a map, or sending on an unbounded channel. For work that needs .await, such as flushing a connection, prefer cooperative cancellation. The task watches a signal, finishes its cleanup in normal async code, and returns. The graceful shutdown chapter builds on this.
Checklist
- For every future inside
select!ortimeout, check its "Cancel safety" section in the docs. - Keep partial progress in variables that outlive the future.
- Pin long-lived futures outside the loop and select on
&mut. - Use
abort()only on tasks that reach.awaitregularly, and checkis_cancelled(). - Put synchronous cleanup in
Drop, and use signals for async cleanup.
Exercise
A loop uses select! with two branches: line = reader.read_line(&mut s) and _ = tick.tick(). Some input lines arrive truncated. Why does this happen, and how would you fix it?
Show answer
readline is not cancel safe. Each time the tick branch wins, the readline future is dropped, and the loop creates a new one on the next iteration. Bytes the dropped future had already consumed are lost or end up split from the rest of the line. Fix it by creating the read_line future once and pinning it outside the loop (selecting on &mut fut), or by moving the reading into its own task that sends complete lines over a channel.
Exercise
You call handle.abort() on a spawned task and then handle.await. What can the result be, and how do you tell the cases apart?
Show answer
If the task was cancelled, the result is Err(JoinError) and is_cancelled() returns true. If the task panicked, it is also Err(JoinError), but is_panic() returns true. If the task finished before abort took effect, the result is Ok with the task's return value.