Struct std::thread_local::KeyExperimental [-]  [+] [src]

pub struct Key<T> {
    // some fields omitted
}

A thread local storage key which owns its contents.

This key uses the fastest possible implementation available to it for the target platform. It is instantiated with the thread_local! macro and the primary method is the with method.

The with method yields a reference to the contained value which cannot be sent across tasks or escape the given closure.

Initialization and Destruction

Initialization is dynamically performed on the first call to with() within a thread, and values support destructors which will be run when a thread exits.

Example

fn main() { use std::cell::RefCell; use std::thread::Thread; thread_local!(static FOO: RefCell<uint> = 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 Thread::spawn(move|| { FOO.with(|f| { assert_eq!(*f.borrow(), 1); *f.borrow_mut() = 3; }); }).detach(); // we retain our original value of 2 despite the child thread FOO.with(|f| { assert_eq!(*f.borrow(), 2); }); }
use std::cell::RefCell;
use std::thread::Thread;

thread_local!(static FOO: RefCell<uint> = 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
Thread::spawn(move|| {
    FOO.with(|f| {
        assert_eq!(*f.borrow(), 1);
        *f.borrow_mut() = 3;
    });
}).detach();

// we retain our original value of 2 despite the child thread
FOO.with(|f| {
    assert_eq!(*f.borrow(), 2);
});

Methods

impl<T: 'static> Key<T>

fn with<F, R>(&'static self, f: F) -> R where F: FnOnce(&T) -> R

Acquire 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.

fn destroyed(&'static self) -> bool

Test this TLS key to determine whether its value has been destroyed for the current thread or not.

This will not initialize the key if it is not already initialized.