Sub topic 10
Cooperative cancellation with CancellationToken
Dropping a future cancels it, which works well for timeout and select!. It does not work for a task that runs on its own, such as a worker loop with state to flush or a connection to close. For those tasks you ask the task to stop and let it choose where and how. This is cooperative cancellation. In the Tokio ecosystem the standard tool is CancellationToken from the tokio-util crate.
This chapter assumes you know tokio::select!, the idea of cancel safety, and tokio::spawn with JoinHandle. It also assumes you have seen why JoinHandle::abort stops a task only at an await point.
Why a token instead of abort
abort is forceful. The task is dropped at its next await point, and you do not control which one. If the task is halfway through writing a batch, the batch is lost. A token reverses the relationship. The owner sets a flag, and the task notices it at points the task itself picks.
| Approach | Who decides where to stop | Typical use |
|---|---|---|
| Drop the future (`timeout`, `select!`) | The caller, at any await point | Bounding a single operation |
| `JoinHandle::abort` | The caller, at the task's next await point | Tasks that hold no state worth saving |
| `CancellationToken` | The task, at checks it writes | Long-lived workers and shutdown |
Add the dependency to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-util = "0.7"The basic API
A CancellationToken is a cheap handle to shared state. Cloning it gives another handle to the same state. These are the methods you will use most:
CancellationToken::new()creates a token that is not cancelled.token.cancel()marks the token cancelled and wakes every waiter. Calling it again does nothing.token.cancelled()returns a future that completes once the token is cancelled. If the token is already cancelled, it completes immediately.token.is_cancelled()is a synchronous check that returns abool.token.child_token()creates a child that is cancelled whenever the parent is.token.drop_guard()returns a guard that cancels the token when it is dropped.
The cancelled() future is cancel safe. You can put it in a select! branch, lose the race, and poll it again later. It holds no data that could be lost. This makes it the natural partner for the select! loops from the previous chapters.
A worker that shuts itself down
The pattern is a loop with a select! that has two kinds of branches. One branch does the work. The other waits for token.cancelled() and breaks out of the loop.
use std::time::Duration;
use tokio::time::sleep;
use tokio_util::sync::CancellationToken;
async fn worker(id: u32, token: CancellationToken) {
loop {
tokio::select! {
_ = token.cancelled() => {
println!("worker {id}: shutting down");
break;
}
_ = sleep(Duration::from_millis(50)) => {
println!("worker {id}: tick");
}
}
}
}
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let handles: Vec<_> = (0..2)
.map(|id| tokio::spawn(worker(id, token.child_token())))
.collect();
sleep(Duration::from_millis(120)).await;
token.cancel();
for handle in handles {
handle.await.unwrap();
}
}Both workers print a couple of ticks, then shutting down after the cancel() call. main waits on the join handles, so the program does not exit until each worker has returned. Without that await, main could finish first and the runtime would drop the workers mid-flight.
What the branch handlers protect
The code inside a branch handler is not part of the raced futures. Once select! picks a winner, it drops the losing futures and then runs the winner's handler as ordinary code. If the sleep branch won, the handler runs to its end even if the token is cancelled while it executes.
That is what lets a worker "finish its current step". Put the unit of work inside the handler, and the cancellation check happens only between units:
use std::time::Duration;
use tokio::{sync::mpsc, time::sleep};
use tokio_util::sync::CancellationToken;
async fn process(job: u32) {
// Stand-in for work that must not be interrupted halfway.
sleep(Duration::from_millis(30)).await;
println!("finished job {job}");
}
async fn run(mut rx: mpsc::Receiver<u32>, token: CancellationToken) {
loop {
tokio::select! {
_ = token.cancelled() => break,
maybe = rx.recv() => match maybe {
Some(job) => process(job).await,
None => break,
},
}
}
println!("run loop exited");
}
#[tokio::main]
async fn main() {
let (tx, rx) = mpsc::channel(8);
let token = CancellationToken::new();
let task = tokio::spawn(run(rx, token.clone()));
tx.send(1).await.unwrap();
tx.send(2).await.unwrap();
sleep(Duration::from_millis(10)).await;
token.cancel();
task.await.unwrap();
}Job 1 is being processed when cancel() runs. It still prints finished job 1, and then the loop sees the cancelled token and exits. Job 2 stays unread in the channel. rx.recv() is cancel safe, so nothing was consumed and lost. If you must drain the queue before exiting, call rx.close() after cancellation and keep receiving until it returns None.
By default select! picks a random ready branch. If both a job and the cancellation are ready, the loop may take one more job before stopping. Add biased; as the first line inside select! to check the token first. Do this only when you want cancellation to win every time.
Token hierarchies
A parent token cancels all of its children. A child token cancels none of its parents. A child can therefore be cancelled alone, which stops one subsystem and leaves the rest running.
Two details matter in practice:
- A child created after its parent was cancelled is cancelled from the start. Its
cancelled()future completes on the first poll, so late-spawned tasks do not hang. - Cloning is different from
child_token(). A clone is the same token, so cancelling it cancels everyone sharing it, including the original. A child has its own state. Useclone()to hand the same signal to several tasks. Usechild_token()when a component may need to be cancelled on its own.
Cancelling work that is not async
cancelled().await cannot interrupt code that never reaches an await point. This is the blocking pitfall from earlier chapters, and a token does not fix it by itself. For CPU-bound or blocking loops, check the flag with is_cancelled() at a sensible granularity:
use std::time::Duration;
use tokio_util::sync::CancellationToken;
fn crunch(token: CancellationToken) -> u64 {
let mut total = 0u64;
for i in 0..u64::MAX {
if i % 1_000_000 == 0 && token.is_cancelled() {
break;
}
total = total.wrapping_add(i);
}
total
}
#[tokio::main]
async fn main() {
let token = CancellationToken::new();
let worker = tokio::task::spawn_blocking({
let token = token.clone();
move || crunch(token)
});
tokio::time::sleep(Duration::from_millis(100)).await;
token.cancel();
let total = worker.await.unwrap();
println!("stopped early with total {total}");
}The check runs once per million iterations, which keeps its cost low while still reacting within milliseconds. Checking on every iteration is correct but slower. Never check less often than the delay you can tolerate. spawn_blocking tasks also cannot be aborted once started, so a flag like this is the only way to stop them early.
Racing a send against cancellation
Cancel safety applies to tokens as well. tx.send(msg).await takes ownership of msg. If you race it against token.cancelled() and the token wins, the send future is dropped and msg is dropped with it. Whether that matters depends on the message. If it does, split the send in two. reserve() waits for channel capacity without taking a message, and permit.send(msg) then completes immediately.
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
async fn send_or_cancel(
tx: &mpsc::Sender<String>,
msg: String,
token: &CancellationToken,
) -> bool {
tokio::select! {
permit = tx.reserve() => match permit {
Ok(p) => {
p.send(msg);
true
}
Err(_) => false,
},
_ = token.cancelled() => false,
}
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel::<String>(1);
let token = CancellationToken::new();
assert!(send_or_cancel(&tx, "first".into(), &token).await);
// The channel is full now, so this call waits until the token fires.
let waiter = {
let tx = tx.clone();
let token = token.clone();
tokio::spawn(async move { send_or_cancel(&tx, "second".into(), &token).await })
};
tokio::task::yield_now().await;
token.cancel();
assert!(!waiter.await.unwrap());
println!("received: {:?}", rx.recv().await);
}In the cancelled branch, msg is still owned by the function when it returns false. The caller passed it in and the function never handed it to the channel, so you can change the signature to return the message in that case if the caller needs it back.
Pitfalls
- Forgetting to wait.
cancel()only sends a signal. It does not wait for anything. Always keep theJoinHandles and await them, or use aTaskTrackerfromtokio-util, if you need to know the work is done. - A worker that never checks. A task that does
loop { rx.recv().await }with no token branch ignores the token. It will stop only if the channel closes. - Checking inside a long handler. If a handler takes minutes, cancellation waits minutes. Split large work into steps and check between them.
- Unbounded shutdown. A stuck worker blocks
handle.awaitforever. Wrap the wait intimeoutand callabort()as a last resort. - Cancelling by drop by accident. A token has no effect when it is dropped. If you want "cancel when this scope exits", use
drop_guard()explicitly.
Exercise
A worker loop runs select! { _ = token.cancelled() => break, job = rx.recv() => handle(job.unwrap()).await }. The parent calls token.cancel() while handle(job) is running. Does handle finish, and what happens to jobs still queued in rx?
Show answer
handle finishes. The raced futures (cancelled() and recv()) are dropped only when select! picks a winner, and the winning branch's handler then runs as normal code that nothing cancels. After handle returns, the next loop iteration sees the cancelled token and breaks. The queued jobs stay in rx unprocessed, since recv() is cancel safe and consumed nothing. To process them, call rx.close() and drain with while let Some(job) = rx.recv().await before exiting.
Exercise
You create let a = token.child_token(); and let b = token.clone();. You call a.cancel(). Which of token, a, and b report is_cancelled() == true?
Show answer
Only a. A child token cancels independently and does not affect its parent. b is a clone, so it shares state with token, and neither was cancelled.