async-cancellation-token 0.1.2

A lightweight single-threaded Rust library for cancellation tokens, enabling cooperative cancellation of asynchronous tasks and callbacks.
Documentation

async-cancellation-token

Crates.io Docs

async-cancellation-token is a lightweight single-threaded Rust library that provides cancellation tokens for cooperative cancellation of asynchronous tasks and callbacks.
It is designed for !Send / single-threaded async environments (e.g., futures::executor::LocalPool).

Features

  • Create a CancellationTokenSource to control cancellation.
  • Generate CancellationTokens to be passed to tasks.
  • Async-aware: token.cancelled().await completes when the token is cancelled.
  • Supports registering callbacks that execute on cancellation.
  • Fully Cloneable and works with Rc/Cell/RefCell.

⚠️ This crate is not thread-safe. Use only in single-threaded async contexts.

Installation

Add this to your Cargo.toml:

[dependencies]
async-cancellation-token = "0.1"

Usage

use async_cancellation_token::{CancellationTokenSource, Cancelled};
use futures::{executor::LocalPool, pin_mut, select, FutureExt};
use futures_timer::Delay;
use std::time::Duration;

let cts = CancellationTokenSource::new();
let token = cts.token();

let mut pool = LocalPool::new();
let spawner = pool.spawner();

spawner.spawn_local(async move {
    for i in 1..=10 {
        let delay = Delay::new(Duration::from_millis(200)).fuse();
        let cancelled = token.cancelled().fuse();
        pin_mut!(delay, cancelled);

        select! {
            _ = delay => println!("Step {i}"),
            _ = cancelled => {
                println!("Cancelled!");
                break;
            }
        }
    }
}.map(|_| ())).unwrap();

// Cancel after 1 second
spawner.spawn_local(async move {
    Delay::new(Duration::from_secs(1)).await;
    cts.cancel();
}.map(|_| ())).unwrap();

pool.run();

API

  • CancellationTokenSource::new() – create a new source.
  • token() – get a CancellationToken.
  • cancel() – cancel all tasks associated with this source.
  • is_cancelled() – check if already cancelled.
  • CancellationToken::cancelled() – returns a Future that resolves on cancellation.
  • CancellationToken::register(f) – register a callback for cancellation.

License

Apache-2.0