Struct async_local::Context
source · pub struct Context<T: Sync>(_);
Expand description
A wrapper around a thread-safe inner type used for creating pointers to thread-locals that are valid for the lifetime of the Tokio runtime and usable within an async context across await points and not reference counted
Implementations§
source§impl<T> Context<T>where
T: Sync,
impl<T> Context<T>where
T: Sync,
sourcepub unsafe fn new(inner: T) -> Context<T>
pub unsafe fn new(inner: T) -> Context<T>
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
.