OS-backed thread-local storage
This crate provides a ThreadLocal
type as an alternative to
std::thread_local!
that allows per-object thread-local storage, while
providing a similar API. It always uses the thread-local storage primitives
provided by the OS.
On Unix systems, pthread-based thread-local storage is used.
On Windows, fiber-local storage is used. This acts like thread-local
storage when fibers are unused, but also provides per-fiber values
after fibers are created with e.g. winapi::um::winbase::CreateFiber
.
The thread_local
crate is an example
of another crate that provides per-object thread-local storage, with a
different API, and different features, but with more performance overhead than
this one.
Examples
This is the same as the example in the std::thread::LocalKey
documentation,
but adjusted to use ThreadLocal
instead. To use it in a static
context, a
lazy initializer, such as once_cell::sync::Lazy
or lazy_static!
is
required.
use RefCell;
use thread;
use Lazy;
use ThreadLocal;
static FOO: =
new;
FOO.with;
// each thread starts out with the initial value of 1
let t = spawn;
// wait for the thread to complete and bail out on panic
t.join.unwrap;
// we retain our original value of 2 despite the child thread
FOO.with;
A variation of the same with scoped threads and per-object thread-local storage:
use RefCell;
use scope;
use ThreadLocal;
let foo = Foo ;
foo.tls.with;
scope.unwrap;