1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Thread local storage
13 #![unstable(feature = "thread_local_internals", issue = "0")]
20 /// A thread local storage key which owns its contents.
22 /// This key uses the fastest possible implementation available to it for the
23 /// target platform. It is instantiated with the [`thread_local!`] macro and the
24 /// primary method is the [`with`] method.
26 /// The [`with`] method yields a reference to the contained value which cannot be
27 /// sent across threads or escape the given closure.
29 /// # Initialization and Destruction
31 /// Initialization is dynamically performed on the first call to [`with`]
32 /// within a thread, and values that implement [`Drop`] get destructed when a
33 /// thread exits. Some caveats apply, which are explained below.
35 /// A `LocalKey`'s initializer cannot recursively depend on itself, and using
36 /// a `LocalKey` in this way will cause the initializer to infinitely recurse
37 /// on the first call to `with`.
42 /// use std::cell::RefCell;
45 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
48 /// assert_eq!(*f.borrow(), 1);
49 /// *f.borrow_mut() = 2;
52 /// // each thread starts out with the initial value of 1
53 /// thread::spawn(move|| {
55 /// assert_eq!(*f.borrow(), 1);
56 /// *f.borrow_mut() = 3;
60 /// // we retain our original value of 2 despite the child thread
62 /// assert_eq!(*f.borrow(), 2);
66 /// # Platform-specific behavior
68 /// Note that a "best effort" is made to ensure that destructors for types
69 /// stored in thread local storage are run, but not all platforms can guarantee
70 /// that destructors will be run for all types in thread local storage. For
71 /// example, there are a number of known caveats where destructors are not run:
73 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
74 /// not be run for TLS values on the main thread when it exits. Note that the
75 /// application will exit immediately after the main thread exits as well.
76 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
77 /// during destruction. Some platforms ensure that this cannot happen
78 /// infinitely by preventing re-initialization of any slot that has been
79 /// destroyed, but not all platforms have this guard. Those platforms that do
80 /// not guard typically have a synthetic limit after which point no more
81 /// destructors are run.
82 /// 3. On macOS, initializing TLS during destruction of other TLS slots can
83 /// sometimes cancel *all* destructors for the current thread, whether or not
84 /// the slots have already had their destructors run or not.
86 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
87 /// [`thread_local!`]: ../../std/macro.thread_local.html
88 /// [`Drop`]: ../../std/ops/trait.Drop.html
89 #[stable(feature = "rust1", since = "1.0.0")]
90 pub struct LocalKey<T: 'static> {
91 // This outer `LocalKey<T>` type is what's going to be stored in statics,
92 // but actual data inside will sometimes be tagged with #[thread_local].
93 // It's not valid for a true static to reference a #[thread_local] static,
94 // so we get around that by exposing an accessor through a layer of function
95 // indirection (this thunk).
97 // Note that the thunk is itself unsafe because the returned lifetime of the
98 // slot where data lives, `'static`, is not actually valid. The lifetime
99 // here is actually slightly shorter than the currently running thread!
101 // Although this is an extra layer of indirection, it should in theory be
102 // trivially devirtualizable by LLVM because the value of `inner` never
103 // changes and the constant should be readonly within a crate. This mainly
104 // only runs into problems when TLS statics are exported across crates.
105 inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
107 // initialization routine to invoke to create a value
111 #[stable(feature = "std_debug", since = "1.16.0")]
112 impl<T: 'static> fmt::Debug for LocalKey<T> {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 f.pad("LocalKey { .. }")
118 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
122 /// The macro wraps any number of static declarations and makes them thread local.
123 /// Publicity and attributes for each static are allowed. Example:
126 /// use std::cell::RefCell;
128 /// pub static FOO: RefCell<u32> = RefCell::new(1);
131 /// static BAR: RefCell<f32> = RefCell::new(1.0);
136 /// See [LocalKey documentation][`std::thread::LocalKey`] for more
139 /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[allow_internal_unstable]
143 macro_rules! thread_local {
144 // empty (base case for the recursion)
147 // process multiple declarations
148 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
149 __thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
150 thread_local!($($rest)*);
153 // handle a single declaration
154 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
155 __thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
160 #[unstable(feature = "thread_local_internals",
161 reason = "should not be necessary",
164 #[allow_internal_unstable]
165 #[allow_internal_unsafe]
166 macro_rules! __thread_local_inner {
167 (@key $(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
170 fn __init() -> $t { $init }
172 unsafe fn __getit() -> $crate::option::Option<
173 &'static $crate::cell::UnsafeCell<
174 $crate::option::Option<$t>>>
176 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
177 static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
178 $crate::thread::__StaticLocalKeyInner::new();
183 not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
185 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
186 $crate::thread::__FastLocalKeyInner::new();
189 not(target_thread_local),
190 not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
192 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
193 $crate::thread::__OsLocalKeyInner::new();
199 $crate::thread::LocalKey::new(__getit, __init)
203 ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
204 $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
205 __thread_local_inner!(@key $(#[$attr])* $vis $name, $t, $init);
209 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
210 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
211 pub struct AccessError {
215 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
216 impl fmt::Debug for AccessError {
217 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
218 f.debug_struct("AccessError").finish()
222 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
223 impl fmt::Display for AccessError {
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 fmt::Display::fmt("already destroyed", f)
229 impl<T: 'static> LocalKey<T> {
231 #[unstable(feature = "thread_local_internals",
232 reason = "recently added to create a key",
234 pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
235 init: fn() -> T) -> LocalKey<T> {
242 /// Acquires a reference to the value in this TLS key.
244 /// This will lazily initialize the value if this thread has not referenced
249 /// This function will `panic!()` if the key currently has its
250 /// destructor running, and it **may** panic if the destructor has
251 /// previously been run for this thread.
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn with<F, R>(&'static self, f: F) -> R
254 where F: FnOnce(&T) -> R {
255 self.try_with(f).expect("cannot access a TLS value during or \
256 after it is destroyed")
259 unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
260 // Execute the initialization up front, *then* move it into our slot,
261 // just in case initialization fails.
262 let value = (self.init)();
263 let ptr = slot.get();
265 // note that this can in theory just be `*ptr = Some(value)`, but due to
266 // the compiler will currently codegen that pattern with something like:
268 // ptr::drop_in_place(ptr)
269 // ptr::write(ptr, Some(value))
271 // Due to this pattern it's possible for the destructor of the value in
272 // `ptr` (e.g. if this is being recursively initialized) to re-access
273 // TLS, in which case there will be a `&` and `&mut` pointer to the same
274 // value (an aliasing violation). To avoid setting the "I'm running a
275 // destructor" flag we just use `mem::replace` which should sequence the
276 // operations a little differently and make this safe to call.
277 mem::replace(&mut *ptr, Some(value));
279 // After storing `Some` we want to get a reference to the contents of
280 // what we just stored. While we could use `unwrap` here and it should
281 // always work it empirically doesn't seem to always get optimized away,
282 // which means that using something like `try_with` can pull in
283 // panicking code and cause a large size bloat.
286 None => hint::unreachable_unchecked(),
290 /// Acquires a reference to the value in this TLS key.
292 /// This will lazily initialize the value if this thread has not referenced
293 /// this key yet. If the key has been destroyed (which may happen if this is called
294 /// in a destructor), this function will return an [`AccessError`](struct.AccessError.html).
298 /// This function will still `panic!()` if the key is uninitialized and the
299 /// key's initializer panics.
300 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
301 pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
306 let slot = (self.inner)().ok_or(AccessError {
309 Ok(f(match *slot.get() {
310 Some(ref inner) => inner,
311 None => self.init(slot),
317 /// On some platforms like wasm32 there's no threads, so no need to generate
318 /// thread locals and we can instead just use plain statics!
320 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
322 use cell::UnsafeCell;
326 inner: UnsafeCell<Option<T>>,
329 unsafe impl<T> ::marker::Sync for Key<T> { }
331 impl<T> fmt::Debug for Key<T> {
332 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
338 pub const fn new() -> Key<T> {
340 inner: UnsafeCell::new(None),
344 pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
345 Some(&*(&self.inner as *const _))
351 #[cfg(target_thread_local)]
353 use cell::{Cell, UnsafeCell};
357 use sys::fast_thread_local::{register_dtor, requires_move_before_drop};
360 inner: UnsafeCell<Option<T>>,
362 // Metadata to keep track of the state of the destructor. Remember that
363 // these variables are thread-local, not global.
364 dtor_registered: Cell<bool>,
365 dtor_running: Cell<bool>,
368 impl<T> fmt::Debug for Key<T> {
369 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
375 pub const fn new() -> Key<T> {
377 inner: UnsafeCell::new(None),
378 dtor_registered: Cell::new(false),
379 dtor_running: Cell::new(false)
383 pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
384 if mem::needs_drop::<T>() && self.dtor_running.get() {
387 self.register_dtor();
388 Some(&*(&self.inner as *const _))
391 unsafe fn register_dtor(&self) {
392 if !mem::needs_drop::<T>() || self.dtor_registered.get() {
396 register_dtor(self as *const _ as *mut u8,
398 self.dtor_registered.set(true);
402 unsafe extern fn destroy_value<T>(ptr: *mut u8) {
403 let ptr = ptr as *mut Key<T>;
404 // Right before we run the user destructor be sure to flag the
405 // destructor as running for this thread so calls to `get` will return
407 (*ptr).dtor_running.set(true);
409 // Some implementations may require us to move the value before we drop
410 // it as it could get re-initialized in-place during destruction.
412 // Hence, we use `ptr::read` on those platforms (to move to a "safe"
413 // location) instead of drop_in_place.
414 if requires_move_before_drop() {
415 ptr::read((*ptr).inner.get());
417 ptr::drop_in_place((*ptr).inner.get());
424 use cell::{Cell, UnsafeCell};
428 use sys_common::thread_local::StaticKey as OsStaticKey;
431 // OS-TLS key that we'll use to key off.
433 marker: marker::PhantomData<Cell<T>>,
436 impl<T> fmt::Debug for Key<T> {
437 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
442 unsafe impl<T> ::marker::Sync for Key<T> { }
444 struct Value<T: 'static> {
445 key: &'static Key<T>,
446 value: UnsafeCell<Option<T>>,
449 impl<T: 'static> Key<T> {
450 pub const fn new() -> Key<T> {
452 os: OsStaticKey::new(Some(destroy_value::<T>)),
453 marker: marker::PhantomData
457 pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
458 let ptr = self.os.get() as *mut Value<T>;
460 if ptr as usize == 1 {
463 return Some(&(*ptr).value);
466 // If the lookup returned null, we haven't initialized our own
467 // local copy, so do that now.
468 let ptr: Box<Value<T>> = box Value {
470 value: UnsafeCell::new(None),
472 let ptr = Box::into_raw(ptr);
473 self.os.set(ptr as *mut u8);
478 unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
479 // The OS TLS ensures that this key contains a NULL value when this
480 // destructor starts to run. We set it back to a sentinel value of 1 to
481 // ensure that any future calls to `get` for this thread will return
484 // Note that to prevent an infinite loop we reset it back to null right
485 // before we return from the destructor ourselves.
486 let ptr = Box::from_raw(ptr as *mut Value<T>);
488 key.os.set(1 as *mut u8);
490 key.os.set(ptr::null_mut());
494 #[cfg(all(test, not(target_os = "emscripten")))]
496 use sync::mpsc::{channel, Sender};
497 use cell::{Cell, UnsafeCell};
500 struct Foo(Sender<()>);
504 let Foo(ref s) = *self;
511 thread_local!(static FOO: Cell<i32> = Cell::new(1));
514 assert_eq!(f.get(), 1);
517 let (tx, rx) = channel();
518 let _t = thread::spawn(move|| {
520 assert_eq!(f.get(), 1);
522 tx.send(()).unwrap();
527 assert_eq!(f.get(), 2);
536 assert!(FOO.try_with(|_| ()).is_err());
539 thread_local!(static FOO: Foo = Foo);
542 assert!(FOO.try_with(|_| ()).is_ok());
543 }).join().ok().unwrap();
548 thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
550 let (tx, rx) = channel();
551 let _t = thread::spawn(move|| unsafe {
552 let mut tx = Some(tx);
554 *f.get() = Some(Foo(tx.take().unwrap()));
564 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
565 thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
566 static mut HITS: u32 = 0;
572 if K2.try_with(|_| ()).is_err() {
576 K2.with(|s| *s.get() = Some(S2));
588 assert!(K1.try_with(|_| ()).is_ok());
590 K1.with(|s| *s.get() = Some(S1));
595 thread::spawn(move|| {
597 }).join().ok().unwrap();
601 fn self_referential() {
603 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
607 assert!(K1.try_with(|_| ()).is_err());
611 thread::spawn(move|| unsafe {
612 K1.with(|s| *s.get() = Some(S1));
613 }).join().ok().unwrap();
616 // Note that this test will deadlock if TLS destructors aren't run (this
617 // requires the destructor to be run to pass the test). macOS has a known bug
618 // where dtors-in-dtors may cancel other destructors, so we just ignore this
621 #[cfg_attr(target_os = "macos", ignore)]
622 fn dtors_in_dtors_in_dtors() {
623 struct S1(Sender<()>);
624 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
625 thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
629 let S1(ref tx) = *self;
631 let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone())));
636 let (tx, rx) = channel();
637 let _t = thread::spawn(move|| unsafe {
638 let mut tx = Some(tx);
639 K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
648 use collections::HashMap;
652 fn square(i: i32) -> i32 { i * i }
653 thread_local!(static FOO: i32 = square(3));
662 fn map() -> RefCell<HashMap<i32, i32>> {
663 let mut m = HashMap::new();
667 thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
670 assert_eq!(map.borrow()[&1], 2);
676 thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
679 assert_eq!(vec.borrow().len(), 3);
680 vec.borrow_mut().push(4);
681 assert_eq!(vec.borrow()[3], 4);