1 //! Thread local storage
3 #![unstable(feature = "thread_local_internals", issue = "none")]
5 #[cfg(all(test, not(target_os = "emscripten")))]
11 use crate::cell::{Cell, RefCell};
12 use crate::error::Error;
15 /// A thread local storage key which owns its contents.
17 /// This key uses the fastest possible implementation available to it for the
18 /// target platform. It is instantiated with the [`thread_local!`] macro and the
19 /// primary method is the [`with`] method.
21 /// The [`with`] method yields a reference to the contained value which cannot be
22 /// sent across threads or escape the given closure.
24 /// [`thread_local!`]: crate::thread_local
26 /// # Initialization and Destruction
28 /// Initialization is dynamically performed on the first call to [`with`]
29 /// within a thread, and values that implement [`Drop`] get destructed when a
30 /// thread exits. Some caveats apply, which are explained below.
32 /// A `LocalKey`'s initializer cannot recursively depend on itself, and using
33 /// a `LocalKey` in this way will cause the initializer to infinitely recurse
34 /// on the first call to `with`.
39 /// use std::cell::RefCell;
42 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
45 /// assert_eq!(*f.borrow(), 1);
46 /// *f.borrow_mut() = 2;
49 /// // each thread starts out with the initial value of 1
50 /// let t = thread::spawn(move|| {
52 /// assert_eq!(*f.borrow(), 1);
53 /// *f.borrow_mut() = 3;
57 /// // wait for the thread to complete and bail out on panic
58 /// t.join().unwrap();
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. When the process exits on Windows systems, TLS destructors may only be
83 /// run on the thread that causes the process to exit. This is because the
84 /// other threads may be forcibly terminated.
86 /// ## Synchronization in thread-local destructors
88 /// On Windows, synchronization operations (such as [`JoinHandle::join`]) in
89 /// thread local destructors are prone to deadlocks and so should be avoided.
90 /// This is because the [loader lock] is held while a destructor is run. The
91 /// lock is acquired whenever a thread starts or exits or when a DLL is loaded
92 /// or unloaded. Therefore these events are blocked for as long as a thread
93 /// local destructor is running.
95 /// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
96 /// [`JoinHandle::join`]: crate::thread::JoinHandle::join
97 /// [`with`]: LocalKey::with
98 #[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
99 #[stable(feature = "rust1", since = "1.0.0")]
100 pub struct LocalKey<T: 'static> {
101 // This outer `LocalKey<T>` type is what's going to be stored in statics,
102 // but actual data inside will sometimes be tagged with #[thread_local].
103 // It's not valid for a true static to reference a #[thread_local] static,
104 // so we get around that by exposing an accessor through a layer of function
105 // indirection (this thunk).
107 // Note that the thunk is itself unsafe because the returned lifetime of the
108 // slot where data lives, `'static`, is not actually valid. The lifetime
109 // here is actually slightly shorter than the currently running thread!
111 // Although this is an extra layer of indirection, it should in theory be
112 // trivially devirtualizable by LLVM because the value of `inner` never
113 // changes and the constant should be readonly within a crate. This mainly
114 // only runs into problems when TLS statics are exported across crates.
115 inner: unsafe fn(Option<&mut Option<T>>) -> Option<&'static T>,
118 #[stable(feature = "std_debug", since = "1.16.0")]
119 impl<T: 'static> fmt::Debug for LocalKey<T> {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.debug_struct("LocalKey").finish_non_exhaustive()
125 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
129 /// The macro wraps any number of static declarations and makes them thread local.
130 /// Publicity and attributes for each static are allowed. Example:
133 /// use std::cell::RefCell;
135 /// pub static FOO: RefCell<u32> = RefCell::new(1);
138 /// static BAR: RefCell<f32> = RefCell::new(1.0);
143 /// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
146 /// [`std::thread::LocalKey`]: crate::thread::LocalKey
148 #[stable(feature = "rust1", since = "1.0.0")]
149 #[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
150 #[allow_internal_unstable(thread_local_internals)]
151 macro_rules! thread_local {
152 // empty (base case for the recursion)
155 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
156 $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
157 $crate::thread_local!($($rest)*);
160 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => (
161 $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
164 // process multiple declarations
165 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
166 $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
167 $crate::thread_local!($($rest)*);
170 // handle a single declaration
171 ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
172 $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
177 #[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "none")]
179 #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)]
180 #[allow_internal_unsafe]
181 macro_rules! __thread_local_inner {
182 // used to generate the `LocalKey` value for const-initialized thread locals
183 (@key $t:ty, const $init:expr) => {{
184 #[cfg_attr(not(all(windows, target_thread_local)), inline)] // see comments below
185 #[cfg_attr(all(windows, target_thread_local), inline(never))]
186 #[deny(unsafe_op_in_unsafe_fn)]
188 _init: $crate::option::Option<&mut $crate::option::Option<$t>>,
189 ) -> $crate::option::Option<&'static $t> {
190 const INIT_EXPR: $t = $init;
192 // wasm without atomics maps directly to `static mut`, and dtors
193 // aren't implemented because thread dtors aren't really a thing
196 // FIXME(#84224) this should come after the `target_thread_local`
198 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
200 static mut VAL: $t = INIT_EXPR;
201 unsafe { $crate::option::Option::Some(&VAL) }
204 // If the platform has support for `#[thread_local]`, use it.
207 not(all(target_family = "wasm", not(target_feature = "atomics"))),
211 static mut VAL: $t = INIT_EXPR;
213 // If a dtor isn't needed we can do something "very raw" and
215 if !$crate::mem::needs_drop::<$t>() {
217 return $crate::option::Option::Some(&VAL)
221 // 0 == dtor not registered
222 // 1 == dtor registered, dtor not run
223 // 2 == dtor registered and is running or has run
225 static mut STATE: $crate::primitive::u8 = 0;
227 unsafe extern "C" fn destroy(ptr: *mut $crate::primitive::u8) {
228 let ptr = ptr as *mut $t;
231 $crate::debug_assert_eq!(STATE, 1);
233 $crate::ptr::drop_in_place(ptr);
239 // 0 == we haven't registered a destructor, so do
242 $crate::thread::__FastLocalKeyInner::<$t>::register_dtor(
243 $crate::ptr::addr_of_mut!(VAL) as *mut $crate::primitive::u8,
247 $crate::option::Option::Some(&VAL)
249 // 1 == the destructor is registered and the value
250 // is valid, so return the pointer.
251 1 => $crate::option::Option::Some(&VAL),
252 // otherwise the destructor has already run, so we
253 // can't give access.
254 _ => $crate::option::Option::None,
259 // On platforms without `#[thread_local]` we fall back to the
260 // same implementation as below for os thread locals.
262 not(target_thread_local),
263 not(all(target_family = "wasm", not(target_feature = "atomics"))),
267 const fn __init() -> $t { INIT_EXPR }
268 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
269 $crate::thread::__OsLocalKeyInner::new();
270 #[allow(unused_unsafe)]
273 if let $crate::option::Option::Some(init) = _init {
274 if let $crate::option::Option::Some(value) = init.take() {
276 } else if $crate::cfg!(debug_assertions) {
277 $crate::unreachable!("missing initial value");
287 $crate::thread::LocalKey::new(__getit)
291 // used to generate the `LocalKey` value for `thread_local!`
292 (@key $t:ty, $init:expr) => {
295 fn __init() -> $t { $init }
297 // When reading this function you might ask "why is this inlined
298 // everywhere other than Windows?", and "why must it not be inlined
299 // on Windows?" and these are very reasonable questions to ask.
301 // The short story is that Windows doesn't support referencing
302 // `#[thread_local]` across DLL boundaries. The slightly longer
303 // story is that each module (dll or exe) has its own separate set
304 // of static thread locals, so if you try and reference a
305 // `#[thread_local]` that comes from `crate1.dll` from within one of
306 // `crate2.dll`'s functions, then it might give you a completely
307 // different thread local than what you asked for (or it might just
310 // Because of this we never inline on Windows, but we do inline on
311 // other platforms (where external references to thread locals
312 // across DLLs are supported). A better fix for this would be to
313 // inline this function on Windows, but only for "statically linked"
314 // components. For example if two separately compiled rlibs end up
315 // getting linked into a DLL then it's fine to inline this function
316 // across that boundary. It's only not fine to inline this function
317 // across a DLL boundary. Unfortunately rustc doesn't currently
318 // have this sort of logic available in an attribute, and it's not
319 // clear that rustc is even equipped to answer this (it's more of a
320 // Cargo question kinda). This means that, unfortunately, Windows
321 // gets the pessimistic path for now where it's never inlined.
323 // The issue of "should improve things on Windows" is #84933
324 #[cfg_attr(not(all(windows, target_thread_local)), inline)]
325 #[cfg_attr(all(windows, target_thread_local), inline(never))]
327 init: $crate::option::Option<&mut $crate::option::Option<$t>>,
328 ) -> $crate::option::Option<&'static $t> {
329 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
330 static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
331 $crate::thread::__StaticLocalKeyInner::new();
336 not(all(target_family = "wasm", not(target_feature = "atomics"))),
338 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
339 $crate::thread::__FastLocalKeyInner::new();
342 not(target_thread_local),
343 not(all(target_family = "wasm", not(target_feature = "atomics"))),
345 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
346 $crate::thread::__OsLocalKeyInner::new();
348 // FIXME: remove the #[allow(...)] marker when macros don't
349 // raise warning for missing/extraneous unsafe blocks anymore.
350 // See https://github.com/rust-lang/rust/issues/74838.
351 #[allow(unused_unsafe)]
354 if let $crate::option::Option::Some(init) = init {
355 if let $crate::option::Option::Some(value) = init.take() {
357 } else if $crate::cfg!(debug_assertions) {
358 $crate::unreachable!("missing default value");
367 $crate::thread::LocalKey::new(__getit)
371 ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $($init:tt)*) => {
372 $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
373 $crate::__thread_local_inner!(@key $t, $($init)*);
377 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
378 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
380 #[derive(Clone, Copy, Eq, PartialEq)]
381 pub struct AccessError;
383 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
384 impl fmt::Debug for AccessError {
385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
386 f.debug_struct("AccessError").finish()
390 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
391 impl fmt::Display for AccessError {
392 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393 fmt::Display::fmt("already destroyed", f)
397 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
398 impl Error for AccessError {}
400 impl<T: 'static> LocalKey<T> {
403 feature = "thread_local_internals",
404 reason = "recently added to create a key",
407 #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
408 pub const unsafe fn new(
409 inner: unsafe fn(Option<&mut Option<T>>) -> Option<&'static T>,
414 /// Acquires a reference to the value in this TLS key.
416 /// This will lazily initialize the value if this thread has not referenced
421 /// This function will `panic!()` if the key currently has its
422 /// destructor running, and it **may** panic if the destructor has
423 /// previously been run for this thread.
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn with<F, R>(&'static self, f: F) -> R
429 self.try_with(f).expect(
430 "cannot access a Thread Local Storage value \
431 during or after destruction",
435 /// Acquires a reference to the value in this TLS key.
437 /// This will lazily initialize the value if this thread has not referenced
438 /// this key yet. If the key has been destroyed (which may happen if this is called
439 /// in a destructor), this function will return an [`AccessError`].
443 /// This function will still `panic!()` if the key is uninitialized and the
444 /// key's initializer panics.
445 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
447 pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
452 let thread_local = (self.inner)(None).ok_or(AccessError)?;
457 /// Acquires a reference to the value in this TLS key, initializing it with
458 /// `init` if it wasn't already initialized on this thread.
460 /// If `init` was used to initialize the thread local variable, `None` is
461 /// passed as the first argument to `f`. If it was already initialized,
462 /// `Some(init)` is passed to `f`.
466 /// This function will panic if the key currently has its destructor
467 /// running, and it **may** panic if the destructor has previously been run
469 fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
471 F: FnOnce(Option<T>, &T) -> R,
474 let mut init = Some(init);
475 let reference = (self.inner)(Some(&mut init)).expect(
476 "cannot access a Thread Local Storage value \
477 during or after destruction",
484 impl<T: 'static> LocalKey<Cell<T>> {
485 /// Sets or initializes the contained value.
487 /// Unlike the other methods, this will *not* run the lazy initializer of
488 /// the thread local. Instead, it will be directly initialized with the
489 /// given value if it wasn't initialized yet.
493 /// Panics if the key currently has its destructor running,
494 /// and it **may** panic if the destructor has previously been run for this thread.
499 /// #![feature(local_key_cell_methods)]
500 /// use std::cell::Cell;
503 /// static X: Cell<i32> = panic!("!");
506 /// // Calling X.get() here would result in a panic.
508 /// X.set(123); // But X.set() is fine, as it skips the initializer above.
510 /// assert_eq!(X.get(), 123);
512 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
513 pub fn set(&'static self, value: T) {
514 self.initialize_with(Cell::new(value), |value, cell| {
515 if let Some(value) = value {
516 // The cell was already initialized, so `value` wasn't used to
517 // initialize it. So we overwrite the current value with the
519 cell.set(value.into_inner());
524 /// Returns a copy of the contained value.
526 /// This will lazily initialize the value if this thread has not referenced
531 /// Panics if the key currently has its destructor running,
532 /// and it **may** panic if the destructor has previously been run for this thread.
537 /// #![feature(local_key_cell_methods)]
538 /// use std::cell::Cell;
541 /// static X: Cell<i32> = Cell::new(1);
544 /// assert_eq!(X.get(), 1);
546 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
547 pub fn get(&'static self) -> T
551 self.with(|cell| cell.get())
554 /// Takes the contained value, leaving `Default::default()` in its place.
556 /// This will lazily initialize the value if this thread has not referenced
561 /// Panics if the key currently has its destructor running,
562 /// and it **may** panic if the destructor has previously been run for this thread.
567 /// #![feature(local_key_cell_methods)]
568 /// use std::cell::Cell;
571 /// static X: Cell<Option<i32>> = Cell::new(Some(1));
574 /// assert_eq!(X.take(), Some(1));
575 /// assert_eq!(X.take(), None);
577 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
578 pub fn take(&'static self) -> T
582 self.with(|cell| cell.take())
585 /// Replaces the contained value, returning the old value.
587 /// This will lazily initialize the value if this thread has not referenced
592 /// Panics if the key currently has its destructor running,
593 /// and it **may** panic if the destructor has previously been run for this thread.
598 /// #![feature(local_key_cell_methods)]
599 /// use std::cell::Cell;
602 /// static X: Cell<i32> = Cell::new(1);
605 /// assert_eq!(X.replace(2), 1);
606 /// assert_eq!(X.replace(3), 2);
608 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
609 pub fn replace(&'static self, value: T) -> T {
610 self.with(|cell| cell.replace(value))
614 impl<T: 'static> LocalKey<RefCell<T>> {
615 /// Acquires a reference to the contained value.
617 /// This will lazily initialize the value if this thread has not referenced
622 /// Panics if the value is currently mutably borrowed.
624 /// Panics if the key currently has its destructor running,
625 /// and it **may** panic if the destructor has previously been run for this thread.
630 /// #![feature(local_key_cell_methods)]
631 /// use std::cell::RefCell;
634 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
637 /// X.with_borrow(|v| assert!(v.is_empty()));
639 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
640 pub fn with_borrow<F, R>(&'static self, f: F) -> R
644 self.with(|cell| f(&cell.borrow()))
647 /// Acquires a mutable reference to the contained value.
649 /// This will lazily initialize the value if this thread has not referenced
654 /// Panics if the value is currently borrowed.
656 /// Panics if the key currently has its destructor running,
657 /// and it **may** panic if the destructor has previously been run for this thread.
662 /// #![feature(local_key_cell_methods)]
663 /// use std::cell::RefCell;
666 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
669 /// X.with_borrow_mut(|v| v.push(1));
671 /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
673 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
674 pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
676 F: FnOnce(&mut T) -> R,
678 self.with(|cell| f(&mut cell.borrow_mut()))
681 /// Sets or initializes the contained value.
683 /// Unlike the other methods, this will *not* run the lazy initializer of
684 /// the thread local. Instead, it will be directly initialized with the
685 /// given value if it wasn't initialized yet.
689 /// Panics if the value is currently borrowed.
691 /// Panics if the key currently has its destructor running,
692 /// and it **may** panic if the destructor has previously been run for this thread.
697 /// #![feature(local_key_cell_methods)]
698 /// use std::cell::RefCell;
701 /// static X: RefCell<Vec<i32>> = panic!("!");
704 /// // Calling X.with() here would result in a panic.
706 /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
708 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
710 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
711 pub fn set(&'static self, value: T) {
712 self.initialize_with(RefCell::new(value), |value, cell| {
713 if let Some(value) = value {
714 // The cell was already initialized, so `value` wasn't used to
715 // initialize it. So we overwrite the current value with the
717 *cell.borrow_mut() = value.into_inner();
722 /// Takes the contained value, leaving `Default::default()` in its place.
724 /// This will lazily initialize the value if this thread has not referenced
729 /// Panics if the value is currently borrowed.
731 /// Panics if the key currently has its destructor running,
732 /// and it **may** panic if the destructor has previously been run for this thread.
737 /// #![feature(local_key_cell_methods)]
738 /// use std::cell::RefCell;
741 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
744 /// X.with_borrow_mut(|v| v.push(1));
746 /// let a = X.take();
748 /// assert_eq!(a, vec![1]);
750 /// X.with_borrow(|v| assert!(v.is_empty()));
752 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
753 pub fn take(&'static self) -> T
757 self.with(|cell| cell.take())
760 /// Replaces the contained value, returning the old value.
764 /// Panics if the value is currently borrowed.
766 /// Panics if the key currently has its destructor running,
767 /// and it **may** panic if the destructor has previously been run for this thread.
772 /// #![feature(local_key_cell_methods)]
773 /// use std::cell::RefCell;
776 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
779 /// let prev = X.replace(vec![1, 2, 3]);
780 /// assert!(prev.is_empty());
782 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
784 #[unstable(feature = "local_key_cell_methods", issue = "92122")]
785 pub fn replace(&'static self, value: T) -> T {
786 self.with(|cell| cell.replace(value))
791 use crate::cell::UnsafeCell;
795 pub struct LazyKeyInner<T> {
796 inner: UnsafeCell<Option<T>>,
799 impl<T> LazyKeyInner<T> {
800 pub const fn new() -> LazyKeyInner<T> {
801 LazyKeyInner { inner: UnsafeCell::new(None) }
804 pub unsafe fn get(&self) -> Option<&'static T> {
805 // SAFETY: The caller must ensure no reference is ever handed out to
806 // the inner cell nor mutable reference to the Option<T> inside said
807 // cell. This make it safe to hand a reference, though the lifetime
808 // of 'static is itself unsafe, making the get method unsafe.
809 unsafe { (*self.inner.get()).as_ref() }
812 /// The caller must ensure that no reference is active: this method
813 /// needs unique access.
814 pub unsafe fn initialize<F: FnOnce() -> T>(&self, init: F) -> &'static T {
815 // Execute the initialization up front, *then* move it into our slot,
816 // just in case initialization fails.
818 let ptr = self.inner.get();
822 // note that this can in theory just be `*ptr = Some(value)`, but due to
823 // the compiler will currently codegen that pattern with something like:
825 // ptr::drop_in_place(ptr)
826 // ptr::write(ptr, Some(value))
828 // Due to this pattern it's possible for the destructor of the value in
829 // `ptr` (e.g., if this is being recursively initialized) to re-access
830 // TLS, in which case there will be a `&` and `&mut` pointer to the same
831 // value (an aliasing violation). To avoid setting the "I'm running a
832 // destructor" flag we just use `mem::replace` which should sequence the
833 // operations a little differently and make this safe to call.
835 // The precondition also ensures that we are the only one accessing
836 // `self` at the moment so replacing is fine.
838 let _ = mem::replace(&mut *ptr, Some(value));
841 // SAFETY: With the call to `mem::replace` it is guaranteed there is
842 // a `Some` behind `ptr`, not a `None` so `unreachable_unchecked`
843 // will never be reached.
845 // After storing `Some` we want to get a reference to the contents of
846 // what we just stored. While we could use `unwrap` here and it should
847 // always work it empirically doesn't seem to always get optimized away,
848 // which means that using something like `try_with` can pull in
849 // panicking code and cause a large size bloat.
852 None => hint::unreachable_unchecked(),
857 /// The other methods hand out references while taking &self.
858 /// As such, callers of this method must ensure no `&` and `&mut` are
859 /// available and used at the same time.
861 pub unsafe fn take(&mut self) -> Option<T> {
862 // SAFETY: See doc comment for this method.
863 unsafe { (*self.inner.get()).take() }
868 /// On some targets like wasm there's no threads, so no need to generate
869 /// thread locals and we can instead just use plain statics!
871 #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
873 use super::lazy::LazyKeyInner;
877 inner: LazyKeyInner<T>,
880 unsafe impl<T> Sync for Key<T> {}
882 impl<T> fmt::Debug for Key<T> {
883 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884 f.debug_struct("Key").finish_non_exhaustive()
889 pub const fn new() -> Key<T> {
890 Key { inner: LazyKeyInner::new() }
893 pub unsafe fn get(&self, init: impl FnOnce() -> T) -> Option<&'static T> {
894 // SAFETY: The caller must ensure no reference is ever handed out to
895 // the inner cell nor mutable reference to the Option<T> inside said
896 // cell. This make it safe to hand a reference, though the lifetime
897 // of 'static is itself unsafe, making the get method unsafe.
899 match self.inner.get() {
900 Some(ref value) => value,
901 None => self.inner.initialize(init),
911 #[cfg(all(target_thread_local, not(all(target_family = "wasm", not(target_feature = "atomics"))),))]
913 use super::lazy::LazyKeyInner;
914 use crate::cell::Cell;
917 use crate::sys::thread_local_dtor::register_dtor;
919 #[derive(Copy, Clone)]
926 // This data structure has been carefully constructed so that the fast path
927 // only contains one branch on x86. That optimization is necessary to avoid
928 // duplicated tls lookups on OSX.
930 // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
932 // If `LazyKeyInner::get` returns `None`, that indicates either:
933 // * The value has never been initialized
934 // * The value is being recursively initialized
935 // * The value has already been destroyed or is being destroyed
936 // To determine which kind of `None`, check `dtor_state`.
938 // This is very optimizer friendly for the fast path - initialized but
940 inner: LazyKeyInner<T>,
942 // Metadata to keep track of the state of the destructor. Remember that
943 // this variable is thread-local, not global.
944 dtor_state: Cell<DtorState>,
947 impl<T> fmt::Debug for Key<T> {
948 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949 f.debug_struct("Key").finish_non_exhaustive()
954 pub const fn new() -> Key<T> {
955 Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) }
958 // note that this is just a publicly-callable function only for the
959 // const-initialized form of thread locals, basically a way to call the
960 // free `register_dtor` function defined elsewhere in libstd.
961 pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
963 register_dtor(a, dtor);
967 pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
968 // SAFETY: See the definitions of `LazyKeyInner::get` and
969 // `try_initialize` for more information.
971 // The caller must ensure no mutable references are ever active to
972 // the inner cell or the inner T when this is called.
973 // The `try_initialize` is dependant on the passed `init` function
976 match self.inner.get() {
977 Some(val) => Some(val),
978 None => self.try_initialize(init),
983 // `try_initialize` is only called once per fast thread local variable,
984 // except in corner cases where thread_local dtors reference other
985 // thread_local's, or it is being recursively initialized.
987 // Macos: Inlining this function can cause two `tlv_get_addr` calls to
988 // be performed for every call to `Key::get`.
989 // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
991 unsafe fn try_initialize<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
992 // SAFETY: See comment above (this function doc).
993 if !mem::needs_drop::<T>() || unsafe { self.try_register_dtor() } {
994 // SAFETY: See comment above (this function doc).
995 Some(unsafe { self.inner.initialize(init) })
1001 // `try_register_dtor` is only called once per fast thread local
1002 // variable, except in corner cases where thread_local dtors reference
1003 // other thread_local's, or it is being recursively initialized.
1004 unsafe fn try_register_dtor(&self) -> bool {
1005 match self.dtor_state.get() {
1006 DtorState::Unregistered => {
1007 // SAFETY: dtor registration happens before initialization.
1008 // Passing `self` as a pointer while using `destroy_value<T>`
1009 // is safe because the function will build a pointer to a
1010 // Key<T>, which is the type of self and so find the correct
1012 unsafe { register_dtor(self as *const _ as *mut u8, destroy_value::<T>) };
1013 self.dtor_state.set(DtorState::Registered);
1016 DtorState::Registered => {
1017 // recursively initialized
1020 DtorState::RunningOrHasRun => false,
1025 unsafe extern "C" fn destroy_value<T>(ptr: *mut u8) {
1026 let ptr = ptr as *mut Key<T>;
1030 // The pointer `ptr` has been built just above and comes from
1031 // `try_register_dtor` where it is originally a Key<T> coming from `self`,
1032 // making it non-NUL and of the correct type.
1034 // Right before we run the user destructor be sure to set the
1035 // `Option<T>` to `None`, and `dtor_state` to `RunningOrHasRun`. This
1036 // causes future calls to `get` to run `try_initialize_drop` again,
1037 // which will now fail, and return `None`.
1039 let value = (*ptr).inner.take();
1040 (*ptr).dtor_state.set(DtorState::RunningOrHasRun);
1048 not(target_thread_local),
1049 not(all(target_family = "wasm", not(target_feature = "atomics"))),
1052 use super::lazy::LazyKeyInner;
1053 use crate::cell::Cell;
1057 use crate::sys_common::thread_local_key::StaticKey as OsStaticKey;
1059 /// Use a regular global static to store this key; the state provided will then be
1062 // OS-TLS key that we'll use to key off.
1064 marker: marker::PhantomData<Cell<T>>,
1067 impl<T> fmt::Debug for Key<T> {
1068 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1069 f.debug_struct("Key").finish_non_exhaustive()
1073 unsafe impl<T> Sync for Key<T> {}
1075 struct Value<T: 'static> {
1076 inner: LazyKeyInner<T>,
1077 key: &'static Key<T>,
1080 impl<T: 'static> Key<T> {
1081 #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
1082 pub const fn new() -> Key<T> {
1083 Key { os: OsStaticKey::new(Some(destroy_value::<T>)), marker: marker::PhantomData }
1086 /// It is a requirement for the caller to ensure that no mutable
1087 /// reference is active when this method is called.
1088 pub unsafe fn get(&'static self, init: impl FnOnce() -> T) -> Option<&'static T> {
1089 // SAFETY: See the documentation for this method.
1090 let ptr = unsafe { self.os.get() as *mut Value<T> };
1092 // SAFETY: the check ensured the pointer is safe (its destructor
1093 // is not running) + it is coming from a trusted source (self).
1094 if let Some(ref value) = unsafe { (*ptr).inner.get() } {
1098 // SAFETY: At this point we are sure we have no value and so
1099 // initializing (or trying to) is safe.
1100 unsafe { self.try_initialize(init) }
1103 // `try_initialize` is only called once per os thread local variable,
1104 // except in corner cases where thread_local dtors reference other
1105 // thread_local's, or it is being recursively initialized.
1106 unsafe fn try_initialize(&'static self, init: impl FnOnce() -> T) -> Option<&'static T> {
1107 // SAFETY: No mutable references are ever handed out meaning getting
1109 let ptr = unsafe { self.os.get() as *mut Value<T> };
1110 if ptr.addr() == 1 {
1111 // destructor is running
1115 let ptr = if ptr.is_null() {
1116 // If the lookup returned null, we haven't initialized our own
1117 // local copy, so do that now.
1118 let ptr: Box<Value<T>> = box Value { inner: LazyKeyInner::new(), key: self };
1119 let ptr = Box::into_raw(ptr);
1120 // SAFETY: At this point we are sure there is no value inside
1121 // ptr so setting it will not affect anyone else.
1123 self.os.set(ptr as *mut u8);
1127 // recursive initialization
1131 // SAFETY: ptr has been ensured as non-NUL just above an so can be
1132 // dereferenced safely.
1133 unsafe { Some((*ptr).inner.initialize(init)) }
1137 unsafe extern "C" fn destroy_value<T: 'static>(ptr: *mut u8) {
1140 // The OS TLS ensures that this key contains a null value when this
1141 // destructor starts to run. We set it back to a sentinel value of 1 to
1142 // ensure that any future calls to `get` for this thread will return
1145 // Note that to prevent an infinite loop we reset it back to null right
1146 // before we return from the destructor ourselves.
1148 let ptr = Box::from_raw(ptr as *mut Value<T>);
1150 key.os.set(ptr::invalid_mut(1));
1152 key.os.set(ptr::null_mut());