Sub topic 10
Cooperative cancellation with CancellationToken
This chapter assumes you know tokio::select!, tokio::spawn, and what cancel safety means. Dropping a future or aborting a task stops work at the next await point, and the code gets no say in where. A CancellationToken lets the work choose its own stopping point.
Why a token
JoinHandle::abort is blunt. A task that is halfway through a multi-step update can be stopped between steps. With cooperative cancellation, the task watches a signal. When the signal fires, the task decides what to finish and what to skip.
CancellationToken comes from the tokio-util crate, not from tokio. Add both to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-util = "0.7"The core API
CancellationToken::new()creates a token.token.cancel()fires the signal. It is idempotent and takes&self.token.cancelled()returns a future that completes once the token is cancelled. It is cancel safe, so you can use it as aselect!branch.token.is_cancelled()is a synchronous check, useful between steps of non-async work.token.clone()gives another handle to the same token. Cancelling any clone cancels all of them.token.child_token()creates a token that is cancelled when its parent is. Cancelling the child does not affect the parent.
Workers that watch a token
Each worker races its normal work against token.cancelled(). The select! runs inside a loop, so the worker keeps going until the token fires.
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();
}
}main cancels the parent token after 120 ms. Each worker sees its child token fire and breaks out of the loop. main then awaits every JoinHandle, so it does not exit before the workers finish. If you skip that step, the runtime may shut down while workers are still running.
Where cancellation takes effect
The worker above only checks the token when the select! runs. Anything inside a branch body runs to completion, because a branch body is not raced. This is the useful property. The tick handler finishes its whole step before the loop looks at the token again.
The exception is a long await inside a body. If a body awaits something slow, the token is ignored until that await returns. To make a slow step interruptible, put a select! around that step as well.
Combining a token with sends
A cancellable send is a good case for the token. Racing tx.send(msg) against token.cancelled() can lose msg if the cancel branch wins, because the send future owns the message and is dropped. Reserve a permit first. The race then drops only the reservation, and you keep msg.
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,
}
}Common mistakes
- Cancelling the token and then returning from
mainwithout awaiting the handles. The workers never get to finish. - Calling
is_cancelled()only at the top of a long async step. The check is a snapshot, so usecancelled()in aselect!for waiting. - Sharing one token where you need independent control. Use
child_token()so one subsystem can stop without stopping everything.
Exercise
In the worker example, you replace token.child_token() with token.clone() and then call cancel() on one of the clones. What happens to the other worker, and how does using child tokens differ when you cancel only a child?
Show answer
Cancelling any clone cancels the shared token, so both workers stop. With child tokens, cancelling the parent stops both children, but cancelling one child stops only the worker holding that child. The parent and the sibling keep running.