pub struct CancellationToken { /* private fields */ }Expand description
A cheap, clonable handle used to request cooperative cancellation of a run.
Cloning a token is O(1) (an Arc bump) and every clone observes the
same underlying state: cancelling any clone cancels them all. Cancellation
is latching — once requested it can never be undone — so a token only ever
transitions from “live” to “cancelled”.
Construct a fresh, never-cancelled token with CancellationToken::new
(or Default). Attach one to a run via
crate::harness::context::RunContext::with_cancellation; the default
RunContext carries a fresh token
that is never cancelled, so cancellation is strictly opt-in.
§Example
use tinyagents::harness::cancel::CancellationToken;
let token = CancellationToken::new();
assert!(!token.is_cancelled());
let clone = token.clone();
clone.cancel();
assert!(token.is_cancelled()); // visible through every cloneImplementations§
Source§impl CancellationToken
impl CancellationToken
Sourcepub fn cancel(&self)
pub fn cancel(&self)
Requests cancellation.
This latches the token into the cancelled state (it can never be
undone) and wakes every task currently awaiting
CancellationToken::cancelled. Calling cancel more than once is
harmless and idempotent. Because every clone shares one state, this
cancels the token observed through all clones.
Sourcepub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Returns true once CancellationToken::cancel has been called on this
token or any of its clones.
Sourcepub async fn cancelled(&self)
pub async fn cancelled(&self)
Resolves as soon as the token is (or becomes) cancelled.
If the token is already cancelled the returned future completes
immediately. Otherwise it parks until CancellationToken::cancel is
called. The implementation registers its interest with the underlying
Notify before re-checking the flag, closing the race where a
cancel lands between the initial check and parking.
This future is cancel-safe and may be used in a select! arm; dropping
it simply deregisters the waiter.
Trait Implementations§
Source§impl Clone for CancellationToken
impl Clone for CancellationToken
Source§fn clone(&self) -> CancellationToken
fn clone(&self) -> CancellationToken
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for CancellationToken
impl Debug for CancellationToken
Source§impl Default for CancellationToken
A Default CancellationToken is a fresh, never-cancelled token.
impl Default for CancellationToken
A Default CancellationToken is a fresh, never-cancelled token.