1 //! Thread local storage
3 #![unstable(feature = "thread_local_internals", issue = "0")]
5 use crate::cell::UnsafeCell;
10 /// A thread local storage key which owns its contents.
12 /// This key uses the fastest possible implementation available to it for the
13 /// target platform. It is instantiated with the [`thread_local!`] macro and the
14 /// primary method is the [`with`] method.
16 /// The [`with`] method yields a reference to the contained value which cannot be
17 /// sent across threads or escape the given closure.
19 /// # Initialization and Destruction
21 /// Initialization is dynamically performed on the first call to [`with`]
22 /// within a thread, and values that implement [`Drop`] get destructed when a
23 /// thread exits. Some caveats apply, which are explained below.
25 /// A `LocalKey`'s initializer cannot recursively depend on itself, and using
26 /// a `LocalKey` in this way will cause the initializer to infinitely recurse
27 /// on the first call to `with`.
32 /// use std::cell::RefCell;
35 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
38 /// assert_eq!(*f.borrow(), 1);
39 /// *f.borrow_mut() = 2;
42 /// // each thread starts out with the initial value of 1
43 /// let t = thread::spawn(move|| {
45 /// assert_eq!(*f.borrow(), 1);
46 /// *f.borrow_mut() = 3;
50 /// // wait for the thread to complete and bail out on panic
51 /// t.join().unwrap();
53 /// // we retain our original value of 2 despite the child thread
55 /// assert_eq!(*f.borrow(), 2);
59 /// # Platform-specific behavior
61 /// Note that a "best effort" is made to ensure that destructors for types
62 /// stored in thread local storage are run, but not all platforms can guarantee
63 /// that destructors will be run for all types in thread local storage. For
64 /// example, there are a number of known caveats where destructors are not run:
66 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
67 /// not be run for TLS values on the main thread when it exits. Note that the
68 /// application will exit immediately after the main thread exits as well.
69 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
70 /// during destruction. Some platforms ensure that this cannot happen
71 /// infinitely by preventing re-initialization of any slot that has been
72 /// destroyed, but not all platforms have this guard. Those platforms that do
73 /// not guard typically have a synthetic limit after which point no more
74 /// destructors are run.
76 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
77 /// [`thread_local!`]: ../../std/macro.thread_local.html
78 /// [`Drop`]: ../../std/ops/trait.Drop.html
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct LocalKey<T: 'static> {
81 // This outer `LocalKey<T>` type is what's going to be stored in statics,
82 // but actual data inside will sometimes be tagged with #[thread_local].
83 // It's not valid for a true static to reference a #[thread_local] static,
84 // so we get around that by exposing an accessor through a layer of function
85 // indirection (this thunk).
87 // Note that the thunk is itself unsafe because the returned lifetime of the
88 // slot where data lives, `'static`, is not actually valid. The lifetime
89 // here is actually slightly shorter than the currently running thread!
91 // Although this is an extra layer of indirection, it should in theory be
92 // trivially devirtualizable by LLVM because the value of `inner` never
93 // changes and the constant should be readonly within a crate. This mainly
94 // only runs into problems when TLS statics are exported across crates.
95 inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
97 // initialization routine to invoke to create a value
101 #[stable(feature = "std_debug", since = "1.16.0")]
102 impl<T: 'static> fmt::Debug for LocalKey<T> {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104 f.pad("LocalKey { .. }")
108 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
112 /// The macro wraps any number of static declarations and makes them thread local.
113 /// Publicity and attributes for each static are allowed. Example:
116 /// use std::cell::RefCell;
118 /// pub static FOO: RefCell<u32> = RefCell::new(1);
121 /// static BAR: RefCell<f32> = RefCell::new(1.0);
126 /// See [LocalKey documentation][`std::thread::LocalKey`] for more
129 /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
131 #[stable(feature = "rust1", since = "1.0.0")]
132 #[allow_internal_unstable(thread_local_internals)]
133 macro_rules! thread_local {
134 // empty (base case for the recursion)
137 // process multiple declarations
138 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
139 $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
140 $crate::thread_local!($($rest)*);
143 // handle a single declaration
144 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
145 $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
150 #[unstable(feature = "thread_local_internals",
151 reason = "should not be necessary",
154 #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)]
155 #[allow_internal_unsafe]
156 macro_rules! __thread_local_inner {
157 (@key $(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
160 fn __init() -> $t { $init }
162 unsafe fn __getit() -> $crate::option::Option<
163 &'static $crate::cell::UnsafeCell<
164 $crate::option::Option<$t>>>
166 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
167 static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
168 $crate::thread::__StaticLocalKeyInner::new();
173 not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
175 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
176 $crate::thread::__FastLocalKeyInner::new();
179 not(target_thread_local),
180 not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
182 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
183 $crate::thread::__OsLocalKeyInner::new();
189 $crate::thread::LocalKey::new(__getit, __init)
193 ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
194 $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
195 $crate::__thread_local_inner!(@key $(#[$attr])* $vis $name, $t, $init);
199 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
200 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
201 pub struct AccessError {
205 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
206 impl fmt::Debug for AccessError {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 f.debug_struct("AccessError").finish()
212 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
213 impl fmt::Display for AccessError {
214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
215 fmt::Display::fmt("already destroyed", f)
219 impl<T: 'static> LocalKey<T> {
221 #[unstable(feature = "thread_local_internals",
222 reason = "recently added to create a key",
224 pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
225 init: fn() -> T) -> LocalKey<T> {
232 /// Acquires a reference to the value in this TLS key.
234 /// This will lazily initialize the value if this thread has not referenced
239 /// This function will `panic!()` if the key currently has its
240 /// destructor running, and it **may** panic if the destructor has
241 /// previously been run for this thread.
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn with<F, R>(&'static self, f: F) -> R
244 where F: FnOnce(&T) -> R {
245 self.try_with(f).expect("cannot access a TLS value during or \
246 after it is destroyed")
249 unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
250 // Execute the initialization up front, *then* move it into our slot,
251 // just in case initialization fails.
252 let value = (self.init)();
253 let ptr = slot.get();
255 // note that this can in theory just be `*ptr = Some(value)`, but due to
256 // the compiler will currently codegen that pattern with something like:
258 // ptr::drop_in_place(ptr)
259 // ptr::write(ptr, Some(value))
261 // Due to this pattern it's possible for the destructor of the value in
262 // `ptr` (e.g., if this is being recursively initialized) to re-access
263 // TLS, in which case there will be a `&` and `&mut` pointer to the same
264 // value (an aliasing violation). To avoid setting the "I'm running a
265 // destructor" flag we just use `mem::replace` which should sequence the
266 // operations a little differently and make this safe to call.
267 mem::replace(&mut *ptr, Some(value));
269 // After storing `Some` we want to get a reference to the contents of
270 // what we just stored. While we could use `unwrap` here and it should
271 // always work it empirically doesn't seem to always get optimized away,
272 // which means that using something like `try_with` can pull in
273 // panicking code and cause a large size bloat.
276 None => hint::unreachable_unchecked(),
280 /// Acquires a reference to the value in this TLS key.
282 /// This will lazily initialize the value if this thread has not referenced
283 /// this key yet. If the key has been destroyed (which may happen if this is called
284 /// in a destructor), this function will return an [`AccessError`](struct.AccessError.html).
288 /// This function will still `panic!()` if the key is uninitialized and the
289 /// key's initializer panics.
290 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
291 pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
296 let slot = (self.inner)().ok_or(AccessError {
299 Ok(f(match *slot.get() {
300 Some(ref inner) => inner,
301 None => self.init(slot),
307 /// On some platforms like wasm32 there's no threads, so no need to generate
308 /// thread locals and we can instead just use plain statics!
310 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
312 use crate::cell::UnsafeCell;
316 inner: UnsafeCell<Option<T>>,
319 unsafe impl<T> Sync for Key<T> { }
321 impl<T> fmt::Debug for Key<T> {
322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
328 pub const fn new() -> Key<T> {
330 inner: UnsafeCell::new(None),
334 pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
335 Some(&*(&self.inner as *const _))
341 #[cfg(target_thread_local)]
343 use crate::cell::{Cell, UnsafeCell};
347 use crate::sys::fast_thread_local::{register_dtor, requires_move_before_drop};
350 inner: UnsafeCell<Option<T>>,
352 // Metadata to keep track of the state of the destructor. Remember that
353 // these variables are thread-local, not global.
354 dtor_registered: Cell<bool>,
355 dtor_running: Cell<bool>,
358 impl<T> fmt::Debug for Key<T> {
359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
365 pub const fn new() -> Key<T> {
367 inner: UnsafeCell::new(None),
368 dtor_registered: Cell::new(false),
369 dtor_running: Cell::new(false)
373 pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
374 if mem::needs_drop::<T>() && self.dtor_running.get() {
377 self.register_dtor();
378 Some(&*(&self.inner as *const _))
381 unsafe fn register_dtor(&self) {
382 if !mem::needs_drop::<T>() || self.dtor_registered.get() {
386 register_dtor(self as *const _ as *mut u8,
388 self.dtor_registered.set(true);
392 unsafe extern fn destroy_value<T>(ptr: *mut u8) {
393 let ptr = ptr as *mut Key<T>;
394 // Right before we run the user destructor be sure to flag the
395 // destructor as running for this thread so calls to `get` will return
397 (*ptr).dtor_running.set(true);
399 // Some implementations may require us to move the value before we drop
400 // it as it could get re-initialized in-place during destruction.
402 // Hence, we use `ptr::read` on those platforms (to move to a "safe"
403 // location) instead of drop_in_place.
404 if requires_move_before_drop() {
405 ptr::read((*ptr).inner.get());
407 ptr::drop_in_place((*ptr).inner.get());
414 use crate::cell::{Cell, UnsafeCell};
418 use crate::sys_common::thread_local::StaticKey as OsStaticKey;
421 // OS-TLS key that we'll use to key off.
423 marker: marker::PhantomData<Cell<T>>,
426 impl<T> fmt::Debug for Key<T> {
427 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
432 unsafe impl<T> Sync for Key<T> { }
434 struct Value<T: 'static> {
435 key: &'static Key<T>,
436 value: UnsafeCell<Option<T>>,
439 impl<T: 'static> Key<T> {
440 pub const fn new() -> Key<T> {
442 os: OsStaticKey::new(Some(destroy_value::<T>)),
443 marker: marker::PhantomData
447 pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
448 let ptr = self.os.get() as *mut Value<T>;
450 if ptr as usize == 1 {
453 return Some(&(*ptr).value);
456 // If the lookup returned null, we haven't initialized our own
457 // local copy, so do that now.
458 let ptr: Box<Value<T>> = box Value {
460 value: UnsafeCell::new(None),
462 let ptr = Box::into_raw(ptr);
463 self.os.set(ptr as *mut u8);
468 unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
469 // The OS TLS ensures that this key contains a NULL value when this
470 // destructor starts to run. We set it back to a sentinel value of 1 to
471 // ensure that any future calls to `get` for this thread will return
474 // Note that to prevent an infinite loop we reset it back to null right
475 // before we return from the destructor ourselves.
476 let ptr = Box::from_raw(ptr as *mut Value<T>);
478 key.os.set(1 as *mut u8);
480 key.os.set(ptr::null_mut());
484 #[cfg(all(test, not(target_os = "emscripten")))]
486 use crate::sync::mpsc::{channel, Sender};
487 use crate::cell::{Cell, UnsafeCell};
490 struct Foo(Sender<()>);
494 let Foo(ref s) = *self;
501 thread_local!(static FOO: Cell<i32> = Cell::new(1));
504 assert_eq!(f.get(), 1);
507 let (tx, rx) = channel();
508 let _t = thread::spawn(move|| {
510 assert_eq!(f.get(), 1);
512 tx.send(()).unwrap();
517 assert_eq!(f.get(), 2);
526 assert!(FOO.try_with(|_| ()).is_err());
529 thread_local!(static FOO: Foo = Foo);
532 assert!(FOO.try_with(|_| ()).is_ok());
533 }).join().ok().expect("thread panicked");
538 thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
540 let (tx, rx) = channel();
541 let _t = thread::spawn(move|| unsafe {
542 let mut tx = Some(tx);
544 *f.get() = Some(Foo(tx.take().unwrap()));
554 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
555 thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
556 static mut HITS: u32 = 0;
562 if K2.try_with(|_| ()).is_err() {
566 K2.with(|s| *s.get() = Some(S2));
578 assert!(K1.try_with(|_| ()).is_ok());
580 K1.with(|s| *s.get() = Some(S1));
585 thread::spawn(move|| {
587 }).join().ok().expect("thread panicked");
591 fn self_referential() {
593 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
597 assert!(K1.try_with(|_| ()).is_err());
601 thread::spawn(move|| unsafe {
602 K1.with(|s| *s.get() = Some(S1));
603 }).join().ok().expect("thread panicked");
606 // Note that this test will deadlock if TLS destructors aren't run (this
607 // requires the destructor to be run to pass the test).
609 fn dtors_in_dtors_in_dtors() {
610 struct S1(Sender<()>);
611 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
612 thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
616 let S1(ref tx) = *self;
618 let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone())));
623 let (tx, rx) = channel();
624 let _t = thread::spawn(move|| unsafe {
625 let mut tx = Some(tx);
626 K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
634 use crate::cell::RefCell;
635 use crate::collections::HashMap;
639 fn square(i: i32) -> i32 { i * i }
640 thread_local!(static FOO: i32 = square(3));
649 fn map() -> RefCell<HashMap<i32, i32>> {
650 let mut m = HashMap::new();
654 thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
657 assert_eq!(map.borrow()[&1], 2);
663 thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
666 assert_eq!(vec.borrow().len(), 3);
667 vec.borrow_mut().push(4);
668 assert_eq!(vec.borrow()[3], 4);