tokio_util::sync

Struct CancellationToken

Source
pub struct CancellationToken { /* private fields */ }
Expand description

A token which can be used to signal a cancellation request to one or more tasks.

Tasks can call CancellationToken::cancelled() in order to obtain a Future which will be resolved when cancellation is requested.

Cancellation can be requested through the CancellationToken::cancel method.

§Examples

use tokio::select;
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    let cloned_token = token.clone();

    let join_handle = tokio::spawn(async move {
        // Wait for either cancellation or a very long time
        select! {
            _ = cloned_token.cancelled() => {
                // The token was cancelled
                5
            }
            _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
                99
            }
        }
    });

    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        token.cancel();
    });

    assert_eq!(5, join_handle.await.unwrap());
}

Implementations§

Source§

impl CancellationToken

Source

pub fn new() -> CancellationToken

Creates a new CancellationToken in the non-cancelled state.

Source

pub fn child_token(&self) -> CancellationToken

Creates a CancellationToken which will get cancelled whenever the current token gets cancelled. Unlike a cloned CancellationToken, cancelling a child token does not cancel the parent token.

If the current token is already cancelled, the child token will get returned in cancelled state.

§Examples
use tokio::select;
use tokio_util::sync::CancellationToken;

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    let child_token = token.child_token();

    let join_handle = tokio::spawn(async move {
        // Wait for either cancellation or a very long time
        select! {
            _ = child_token.cancelled() => {
                // The token was cancelled
                5
            }
            _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => {
                99
            }
        }
    });

    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        token.cancel();
    });

    assert_eq!(5, join_handle.await.unwrap());
}
Source

pub fn cancel(&self)

Cancel the CancellationToken and all child tokens which had been derived from it.

This will wake up all tasks which are waiting for cancellation.

Be aware that cancellation is not an atomic operation. It is possible for another thread running in parallel with a call to cancel to first receive true from is_cancelled on one child node, and then receive false from is_cancelled on another child node. However, once the call to cancel returns, all child nodes have been fully cancelled.

Source

pub fn is_cancelled(&self) -> bool

Returns true if the CancellationToken is cancelled.

Source

pub fn cancelled(&self) -> WaitForCancellationFuture<'_>

Returns a Future that gets fulfilled when cancellation is requested.

The future will complete immediately if the token is already cancelled when this method is called.

§Cancel safety

This method is cancel safe.

Source

pub fn cancelled_owned(self) -> WaitForCancellationFutureOwned

Returns a Future that gets fulfilled when cancellation is requested.

The future will complete immediately if the token is already cancelled when this method is called.

The function takes self by value and returns a future that owns the token.

§Cancel safety

This method is cancel safe.

Source

pub fn drop_guard(self) -> DropGuard

Creates a DropGuard for this token.

Returned guard will cancel this token (and all its children) on drop unless disarmed.

Source

pub async fn run_until_cancelled<F>(&self, fut: F) -> Option<F::Output>
where F: Future,

Runs a future to completion and returns its result wrapped inside of an Option unless the CancellationToken is cancelled. In that case the function returns None and the future gets dropped.

§Cancel safety

This method is only cancel safe if fut is cancel safe.

Trait Implementations§

Source§

impl Clone for CancellationToken

Source§

fn clone(&self) -> Self

Creates a clone of the CancellationToken which will get cancelled whenever the current token gets cancelled, and vice versa.

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CancellationToken

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CancellationToken

Source§

fn default() -> CancellationToken

Returns the “default value” for a type. Read more
Source§

impl Drop for CancellationToken

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl RefUnwindSafe for CancellationToken

Source§

impl UnwindSafe for CancellationToken

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...) attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 8 bytes