Struct thread_local_macro::LocalKey
source · pub struct LocalKey<T: 'static> { /* private fields */ }
Expand description
A thread-local storage key which owns its contents.
This TLS object is instantiated the thread_local!
macro and offers
one primary method to access it: the with
method.
The with
method yields a reference to the contained value which cannot be
sent across threads or escape the given closure.
Initialization and Destruction
Initialization is lazily performed dynamically on the first call to with
within a thread (Task
in Theseus), and values that implement Drop
get destructed
when a thread exits.
A LocalKey
’s initializer cannot recursively depend on itself, and using
a LocalKey
in this way will cause the initializer to infinitely recurse
on the first call to with
.
Examples
use core::cell::RefCell;
use spawn::new_task_builder;
thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
FOO.with(|f| {
assert_eq!(*f.borrow(), 1);
*f.borrow_mut() = 2;
});
// each thread starts out with the initial value of 1
let t = new_task_builder(
move |_: ()| {
FOO.with(|f| {
assert_eq!(*f.borrow(), 1);
*f.borrow_mut() = 3;
});
},
(), // empty arg
).spawn().unwrap();
// wait for the new task to exit
t.join();
// we retain our original value of 2 despite the child thread
FOO.with(|f| {
assert_eq!(*f.borrow(), 2);
});
Implementations§
source§impl<T: 'static> LocalKey<T>
impl<T: 'static> LocalKey<T>
sourcepub fn with<F, R>(&'static self, f: F) -> Rwhere
F: FnOnce(&T) -> R,
pub fn with<F, R>(&'static self, f: F) -> Rwhere F: FnOnce(&T) -> R,
Acquires a reference to the value in this TLS key.
This will lazily initialize the value if this thread has not referenced this key yet.
Panics
This function will panic!()
if the key currently has its
destructor running, and it may panic if the destructor has
previously been run for this thread.
sourcepub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>where
F: FnOnce(&T) -> R,
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>where F: FnOnce(&T) -> R,
Acquires a reference to the value in this TLS key.
This will lazily initialize the value if this thread has not referenced
this key yet. If the key has been destroyed (which may happen if this is called
in a destructor), this function will return an AccessError
.
Panics
This function will still panic!()
if the key is uninitialized and the
key’s initializer panics.