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")]
19 /// A thread local storage key which owns its contents.
21 /// This key uses the fastest possible implementation available to it for the
22 /// target platform. It is instantiated with the [`thread_local!`] macro and the
23 /// primary method is the [`with`] method.
25 /// The [`with`] method yields a reference to the contained value which cannot be
26 /// sent across threads or escape the given closure.
28 /// # Initialization and Destruction
30 /// Initialization is dynamically performed on the first call to [`with`]
31 /// within a thread, and values that implement [`Drop`] get destructed when a
32 /// thread exits. Some caveats apply, which are explained below.
37 /// use std::cell::RefCell;
40 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
43 /// assert_eq!(*f.borrow(), 1);
44 /// *f.borrow_mut() = 2;
47 /// // each thread starts out with the initial value of 1
48 /// thread::spawn(move|| {
50 /// assert_eq!(*f.borrow(), 1);
51 /// *f.borrow_mut() = 3;
55 /// // we retain our original value of 2 despite the child thread
57 /// assert_eq!(*f.borrow(), 2);
61 /// # Platform-specific behavior
63 /// Note that a "best effort" is made to ensure that destructors for types
64 /// stored in thread local storage are run, but not all platforms can guarantee
65 /// that destructors will be run for all types in thread local storage. For
66 /// example, there are a number of known caveats where destructors are not run:
68 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
69 /// not be run for TLS values on the main thread when it exits. Note that the
70 /// application will exit immediately after the main thread exits as well.
71 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
72 /// during destruction. Some platforms ensure that this cannot happen
73 /// infinitely by preventing re-initialization of any slot that has been
74 /// destroyed, but not all platforms have this guard. Those platforms that do
75 /// not guard typically have a synthetic limit after which point no more
76 /// destructors are run.
77 /// 3. On macOS, initializing TLS during destruction of other TLS slots can
78 /// sometimes cancel *all* destructors for the current thread, whether or not
79 /// the slots have already had their destructors run or not.
81 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
82 /// [`thread_local!`]: ../../std/macro.thread_local.html
83 /// [`Drop`]: ../../std/ops/trait.Drop.html
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct LocalKey<T: 'static> {
86 // This outer `LocalKey<T>` type is what's going to be stored in statics,
87 // but actual data inside will sometimes be tagged with #[thread_local].
88 // It's not valid for a true static to reference a #[thread_local] static,
89 // so we get around that by exposing an accessor through a layer of function
90 // indirection (this thunk).
92 // Note that the thunk is itself unsafe because the returned lifetime of the
93 // slot where data lives, `'static`, is not actually valid. The lifetime
94 // here is actually `'thread`!
96 // Although this is an extra layer of indirection, it should in theory be
97 // trivially devirtualizable by LLVM because the value of `inner` never
98 // changes and the constant should be readonly within a crate. This mainly
99 // only runs into problems when TLS statics are exported across crates.
100 inner: fn() -> Option<&'static UnsafeCell<Option<T>>>,
102 // initialization routine to invoke to create a value
106 #[stable(feature = "std_debug", since = "1.16.0")]
107 impl<T: 'static> fmt::Debug for LocalKey<T> {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 f.pad("LocalKey { .. }")
114 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
118 /// The macro wraps any number of static declarations and makes them thread local.
119 /// Publicity and attributes for each static are allowed. Example:
122 /// use std::cell::RefCell;
124 /// pub static FOO: RefCell<u32> = RefCell::new(1);
127 /// static BAR: RefCell<f32> = RefCell::new(1.0);
132 /// See [LocalKey documentation][`std::thread::LocalKey`] for more
135 /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
137 #[stable(feature = "rust1", since = "1.0.0")]
138 #[allow_internal_unstable]
139 macro_rules! thread_local {
140 // empty (base case for the recursion)
143 // process multiple declarations
144 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
145 __thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
146 thread_local!($($rest)*);
149 // handle a single declaration
150 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
151 __thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
157 #[unstable(feature = "thread_local_internals",
158 reason = "should not be necessary",
161 #[allow_internal_unstable]
162 macro_rules! __thread_local_inner {
163 ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
164 $(#[$attr])* $vis static $name: $crate::thread::LocalKey<$t> = {
165 fn __init() -> $t { $init }
167 fn __getit() -> $crate::option::Option<
168 &'static $crate::cell::UnsafeCell<
169 $crate::option::Option<$t>>>
172 #[cfg(target_thread_local)]
173 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
174 $crate::thread::__FastLocalKeyInner::new();
176 #[cfg(not(target_thread_local))]
177 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
178 $crate::thread::__OsLocalKeyInner::new();
183 $crate::thread::LocalKey::new(__getit, __init)
189 /// Declare a new thread local storage key of type `std::thread::LocalKey`.
191 #[stable(feature = "rust1", since = "1.0.0")]
192 #[allow_internal_unstable]
193 macro_rules! thread_local {
194 // rule 0: empty (base case for the recursion)
197 // rule 1: process multiple declarations where the first one is private
198 ($(#[$attr:meta])* static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
199 thread_local!($(#[$attr])* static $name: $t = $init); // go to rule 2
200 thread_local!($($rest)*);
203 // rule 2: handle a single private declaration
204 ($(#[$attr:meta])* static $name:ident: $t:ty = $init:expr) => (
205 $(#[$attr])* static $name: $crate::thread::LocalKey<$t> =
206 __thread_local_inner!($t, $init);
209 // rule 3: handle multiple declarations where the first one is public
210 ($(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
211 thread_local!($(#[$attr])* pub static $name: $t = $init); // go to rule 4
212 thread_local!($($rest)*);
215 // rule 4: handle a single public declaration
216 ($(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr) => (
217 $(#[$attr])* pub static $name: $crate::thread::LocalKey<$t> =
218 __thread_local_inner!($t, $init);
224 #[unstable(feature = "thread_local_internals",
225 reason = "should not be necessary",
228 #[allow_internal_unstable]
229 macro_rules! __thread_local_inner {
230 ($t:ty, $init:expr) => {{
231 fn __init() -> $t { $init }
233 fn __getit() -> $crate::option::Option<
234 &'static $crate::cell::UnsafeCell<
235 $crate::option::Option<$t>>>
238 #[cfg(target_thread_local)]
239 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
240 $crate::thread::__FastLocalKeyInner::new();
242 #[cfg(not(target_thread_local))]
243 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
244 $crate::thread::__OsLocalKeyInner::new();
249 $crate::thread::LocalKey::new(__getit, __init)
253 /// Indicator of the state of a thread local storage key.
254 #[unstable(feature = "thread_local_state",
255 reason = "state querying was recently added",
257 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
258 pub enum LocalKeyState {
259 /// All keys are in this state whenever a thread starts. Keys will
260 /// transition to the `Valid` state once the first call to [`with`] happens
261 /// and the initialization expression succeeds.
263 /// Keys in the `Uninitialized` state will yield a reference to the closure
264 /// passed to [`with`] so long as the initialization routine does not panic.
266 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
269 /// Once a key has been accessed successfully, it will enter the `Valid`
270 /// state. Keys in the `Valid` state will remain so until the thread exits,
271 /// at which point the destructor will be run and the key will enter the
272 /// `Destroyed` state.
274 /// Keys in the `Valid` state will be guaranteed to yield a reference to the
275 /// closure passed to [`with`].
277 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
280 /// When a thread exits, the destructors for keys will be run (if
281 /// necessary). While a destructor is running, and possibly after a
282 /// destructor has run, a key is in the `Destroyed` state.
284 /// Keys in the `Destroyed` states will trigger a panic when accessed via
287 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
291 impl<T: 'static> LocalKey<T> {
293 #[unstable(feature = "thread_local_internals",
294 reason = "recently added to create a key",
296 pub const fn new(inner: fn() -> Option<&'static UnsafeCell<Option<T>>>,
297 init: fn() -> T) -> LocalKey<T> {
304 /// Acquires a reference to the value in this TLS key.
306 /// This will lazily initialize the value if this thread has not referenced
311 /// This function will `panic!()` if the key currently has its
312 /// destructor running, and it **may** panic if the destructor has
313 /// previously been run for this thread.
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn with<F, R>(&'static self, f: F) -> R
316 where F: FnOnce(&T) -> R {
318 let slot = (self.inner)();
319 let slot = slot.expect("cannot access a TLS value during or \
320 after it is destroyed");
321 f(match *slot.get() {
322 Some(ref inner) => inner,
323 None => self.init(slot),
328 unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
329 // Execute the initialization up front, *then* move it into our slot,
330 // just in case initialization fails.
331 let value = (self.init)();
332 let ptr = slot.get();
334 // note that this can in theory just be `*ptr = Some(value)`, but due to
335 // the compiler will currently codegen that pattern with something like:
337 // ptr::drop_in_place(ptr)
338 // ptr::write(ptr, Some(value))
340 // Due to this pattern it's possible for the destructor of the value in
341 // `ptr` (e.g. if this is being recursively initialized) to re-access
342 // TLS, in which case there will be a `&` and `&mut` pointer to the same
343 // value (an aliasing violation). To avoid setting the "I'm running a
344 // destructor" flag we just use `mem::replace` which should sequence the
345 // operations a little differently and make this safe to call.
346 mem::replace(&mut *ptr, Some(value));
348 (*ptr).as_ref().unwrap()
351 /// Query the current state of this key.
353 /// A key is initially in the `Uninitialized` state whenever a thread
354 /// starts. It will remain in this state up until the first call to [`with`]
355 /// within a thread has run the initialization expression successfully.
357 /// Once the initialization expression succeeds, the key transitions to the
358 /// `Valid` state which will guarantee that future calls to [`with`] will
359 /// succeed within the thread.
361 /// When a thread exits, each key will be destroyed in turn, and as keys are
362 /// destroyed they will enter the `Destroyed` state just before the
363 /// destructor starts to run. Keys may remain in the `Destroyed` state after
364 /// destruction has completed. Keys without destructors (e.g. with types
365 /// that are [`Copy`]), may never enter the `Destroyed` state.
367 /// Keys in the `Uninitialized` state can be accessed so long as the
368 /// initialization does not panic. Keys in the `Valid` state are guaranteed
369 /// to be able to be accessed. Keys in the `Destroyed` state will panic on
370 /// any call to [`with`].
372 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
373 /// [`Copy`]: ../../std/marker/trait.Copy.html
374 #[unstable(feature = "thread_local_state",
375 reason = "state querying was recently added",
377 pub fn state(&'static self) -> LocalKeyState {
379 match (self.inner)() {
382 Some(..) => LocalKeyState::Valid,
383 None => LocalKeyState::Uninitialized,
386 None => LocalKeyState::Destroyed,
393 #[cfg(target_thread_local)]
395 use cell::{Cell, UnsafeCell};
399 use sys::fast_thread_local::{register_dtor, requires_move_before_drop};
402 inner: UnsafeCell<Option<T>>,
404 // Metadata to keep track of the state of the destructor. Remember that
405 // these variables are thread-local, not global.
406 dtor_registered: Cell<bool>,
407 dtor_running: Cell<bool>,
410 impl<T> fmt::Debug for Key<T> {
411 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
416 unsafe impl<T> ::marker::Sync for Key<T> { }
419 pub const fn new() -> Key<T> {
421 inner: UnsafeCell::new(None),
422 dtor_registered: Cell::new(false),
423 dtor_running: Cell::new(false)
427 pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
429 if mem::needs_drop::<T>() && self.dtor_running.get() {
432 self.register_dtor();
437 unsafe fn register_dtor(&self) {
438 if !mem::needs_drop::<T>() || self.dtor_registered.get() {
442 register_dtor(self as *const _ as *mut u8,
444 self.dtor_registered.set(true);
448 unsafe extern fn destroy_value<T>(ptr: *mut u8) {
449 let ptr = ptr as *mut Key<T>;
450 // Right before we run the user destructor be sure to flag the
451 // destructor as running for this thread so calls to `get` will return
453 (*ptr).dtor_running.set(true);
455 // Some implementations may require us to move the value before we drop
456 // it as it could get re-initialized in-place during destruction.
458 // Hence, we use `ptr::read` on those platforms (to move to a "safe"
459 // location) instead of drop_in_place.
460 if requires_move_before_drop() {
461 ptr::read((*ptr).inner.get());
463 ptr::drop_in_place((*ptr).inner.get());
470 use cell::{Cell, UnsafeCell};
474 use sys_common::thread_local::StaticKey as OsStaticKey;
477 // OS-TLS key that we'll use to key off.
479 marker: marker::PhantomData<Cell<T>>,
482 impl<T> fmt::Debug for Key<T> {
483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
488 unsafe impl<T> ::marker::Sync for Key<T> { }
490 struct Value<T: 'static> {
491 key: &'static Key<T>,
492 value: UnsafeCell<Option<T>>,
495 impl<T: 'static> Key<T> {
496 pub const fn new() -> Key<T> {
498 os: OsStaticKey::new(Some(destroy_value::<T>)),
499 marker: marker::PhantomData
503 pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
505 let ptr = self.os.get() as *mut Value<T>;
507 if ptr as usize == 1 {
510 return Some(&(*ptr).value);
513 // If the lookup returned null, we haven't initialized our own
514 // local copy, so do that now.
515 let ptr: Box<Value<T>> = box Value {
517 value: UnsafeCell::new(None),
519 let ptr = Box::into_raw(ptr);
520 self.os.set(ptr as *mut u8);
526 unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
527 // The OS TLS ensures that this key contains a NULL value when this
528 // destructor starts to run. We set it back to a sentinel value of 1 to
529 // ensure that any future calls to `get` for this thread will return
532 // Note that to prevent an infinite loop we reset it back to null right
533 // before we return from the destructor ourselves.
534 let ptr = Box::from_raw(ptr as *mut Value<T>);
536 key.os.set(1 as *mut u8);
538 key.os.set(ptr::null_mut());
542 #[cfg(all(test, not(target_os = "emscripten")))]
544 use sync::mpsc::{channel, Sender};
545 use cell::{Cell, UnsafeCell};
546 use super::LocalKeyState;
549 struct Foo(Sender<()>);
553 let Foo(ref s) = *self;
560 thread_local!(static FOO: Cell<i32> = Cell::new(1));
563 assert_eq!(f.get(), 1);
566 let (tx, rx) = channel();
567 let _t = thread::spawn(move|| {
569 assert_eq!(f.get(), 1);
571 tx.send(()).unwrap();
576 assert_eq!(f.get(), 2);
585 assert!(FOO.state() == LocalKeyState::Destroyed);
589 assert!(FOO.state() == LocalKeyState::Uninitialized);
592 thread_local!(static FOO: Foo = foo());
595 assert!(FOO.state() == LocalKeyState::Uninitialized);
597 assert!(FOO.state() == LocalKeyState::Valid);
599 assert!(FOO.state() == LocalKeyState::Valid);
600 }).join().ok().unwrap();
605 thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
607 let (tx, rx) = channel();
608 let _t = thread::spawn(move|| unsafe {
609 let mut tx = Some(tx);
611 *f.get() = Some(Foo(tx.take().unwrap()));
621 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
622 thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
623 static mut HITS: u32 = 0;
629 if K2.state() == LocalKeyState::Destroyed {
633 K2.with(|s| *s.get() = Some(S2));
645 assert!(K1.state() != LocalKeyState::Destroyed);
647 K1.with(|s| *s.get() = Some(S1));
652 thread::spawn(move|| {
654 }).join().ok().unwrap();
658 fn self_referential() {
660 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
664 assert!(K1.state() == LocalKeyState::Destroyed);
668 thread::spawn(move|| unsafe {
669 K1.with(|s| *s.get() = Some(S1));
670 }).join().ok().unwrap();
673 // Note that this test will deadlock if TLS destructors aren't run (this
674 // requires the destructor to be run to pass the test). macOS has a known bug
675 // where dtors-in-dtors may cancel other destructors, so we just ignore this
678 #[cfg_attr(target_os = "macos", ignore)]
679 fn dtors_in_dtors_in_dtors() {
680 struct S1(Sender<()>);
681 thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
682 thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
686 let S1(ref tx) = *self;
688 if K2.state() != LocalKeyState::Destroyed {
689 K2.with(|s| *s.get() = Some(Foo(tx.clone())));
695 let (tx, rx) = channel();
696 let _t = thread::spawn(move|| unsafe {
697 let mut tx = Some(tx);
698 K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
707 use collections::HashMap;
711 fn square(i: i32) -> i32 { i * i }
712 thread_local!(static FOO: i32 = square(3));
721 fn map() -> RefCell<HashMap<i32, i32>> {
722 let mut m = HashMap::new();
726 thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
729 assert_eq!(map.borrow()[&1], 2);
735 thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
738 assert_eq!(vec.borrow().len(), 3);
739 vec.borrow_mut().push(4);
740 assert_eq!(vec.borrow()[3], 4);