Struct async_local::Context

source ·
pub struct Context<T: Sync>(_);
Expand description

A wrapper around a thread-safe inner type used for creating stable references to thread-locals that are valid for the lifetime of the Tokio runtime and usable within an async context across await points

Implementations§

Create a new thread-local context

Usage

Either wrap an inner type with Context and assign to a thread-local, or add as an unwrapped field in a struct that implements AsRef<Context<T>>

Example
thread_local! {
  static COUNTER: Context<AtomicUsize> = unsafe { Context::new(|| AtomicUsize::new(0)) };
}
Safety

The only safe way to use Context is within a thread local variable that upholds the pin drop guarantee: it cannot be used nor dropped elsewhere; it cannot be wrapped in a pointer type nor cell type; and it must not be invalidated nor repurposed until when drop happens solely as a consequence of the thread dropping. It does not matter which thread Context is allocated on, and so it is sound to have publicly visible thread locals using Context without concern for visibility, but it must be guaranteed that references never exist outside of nor outlive the Tokio runtime by upholding the gaurantees enumerated within AsyncLocal governing the safe usage of LocalRef and RefGuard.

Trait Implementations§

Converts this type into a shared reference of the (usually inferred) input type.
The resulting type after dereferencing.
Dereferences the value.

This ensures that during the Tokio runtime shutdown sequence all tasks are dropped before any thread drops and that dereferencing during drop is always sound.

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.