Struct std::thread::ScopedKey
[−]
[src]
pub struct ScopedKey<T: 'static> { // some fields omitted }
: hasn't proven itself over LocalKey
Type representing a thread local storage key corresponding to a reference
to the type parameter T
.
Keys are statically allocated and can contain a reference to an instance of
type T
scoped to a particular lifetime. Keys provides two methods, set
and with
, both of which currently use closures to control the scope of
their contents.
Methods
impl<T> ScopedKey<T>
fn set<R, F>(&'static self, t: &T, cb: F) -> R where F: FnOnce() -> R
: hasn't proven itself over LocalKey
Inserts a value into this scoped thread local storage slot for a duration of a closure.
While cb
is running, the value t
will be returned by get
unless
this function is called recursively inside of cb
.
Upon return, this function will restore the previous value, if any was available.
Examples
#![feature(scoped_tls)] fn main() { scoped_thread_local!(static FOO: u32); FOO.set(&100, || { let val = FOO.with(|v| *v); assert_eq!(val, 100); // set can be called recursively FOO.set(&101, || { // ... }); // Recursive calls restore the previous value. let val = FOO.with(|v| *v); assert_eq!(val, 100); }); }#![feature(scoped_tls)] scoped_thread_local!(static FOO: u32); FOO.set(&100, || { let val = FOO.with(|v| *v); assert_eq!(val, 100); // set can be called recursively FOO.set(&101, || { // ... }); // Recursive calls restore the previous value. let val = FOO.with(|v| *v); assert_eq!(val, 100); });
fn with<R, F>(&'static self, cb: F) -> R where F: FnOnce(&T) -> R
: hasn't proven itself over LocalKey
Gets a value out of this scoped variable.
This function takes a closure which receives the value of this variable.
Panics
This function will panic if set
has not previously been called.
Examples
#![feature(scoped_tls)] fn main() { scoped_thread_local!(static FOO: u32); FOO.with(|slot| { // work with `slot` }); }#![feature(scoped_tls)] scoped_thread_local!(static FOO: u32); FOO.with(|slot| { // work with `slot` });
fn is_set(&'static self) -> bool
: hasn't proven itself over LocalKey
Test whether this TLS key has been set
for the current thread.