std/thread/
local.rs

1//! Thread local storage
2
3#![unstable(feature = "thread_local_internals", issue = "none")]
4
5use crate::cell::{Cell, RefCell};
6use crate::error::Error;
7use crate::fmt;
8
9/// A thread local storage (TLS) key which owns its contents.
10///
11/// This key uses the fastest possible implementation available to it for the
12/// target platform. It is instantiated with the [`thread_local!`] macro and the
13/// primary method is the [`with`] method, though there are helpers to make
14/// working with [`Cell`] types easier.
15///
16/// The [`with`] method yields a reference to the contained value which cannot
17/// outlive the current thread or escape the given closure.
18///
19/// [`thread_local!`]: crate::thread_local
20///
21/// # Initialization and Destruction
22///
23/// Initialization is dynamically performed on the first call to a setter (e.g.
24/// [`with`]) within a thread, and values that implement [`Drop`] get
25/// destructed when a thread exits. Some caveats apply, which are explained below.
26///
27/// A `LocalKey`'s initializer cannot recursively depend on itself. Using a
28/// `LocalKey` in this way may cause panics, aborts or infinite recursion on
29/// the first call to `with`.
30///
31/// # Single-thread Synchronization
32///
33/// Though there is no potential race with other threads, it is still possible to
34/// obtain multiple references to the thread-local data in different places on
35/// the call stack. For this reason, only shared (`&T`) references may be obtained.
36///
37/// To allow obtaining an exclusive mutable reference (`&mut T`), typically a
38/// [`Cell`] or [`RefCell`] is used (see the [`std::cell`] for more information
39/// on how exactly this works). To make this easier there are specialized
40/// implementations for [`LocalKey<Cell<T>>`] and [`LocalKey<RefCell<T>>`].
41///
42/// [`std::cell`]: `crate::cell`
43/// [`LocalKey<Cell<T>>`]: struct.LocalKey.html#impl-LocalKey<Cell<T>>
44/// [`LocalKey<RefCell<T>>`]: struct.LocalKey.html#impl-LocalKey<RefCell<T>>
45///
46///
47/// # Examples
48///
49/// ```
50/// use std::cell::Cell;
51/// use std::thread;
52///
53/// // explicit `const {}` block enables more efficient initialization
54/// thread_local!(static FOO: Cell<u32> = const { Cell::new(1) });
55///
56/// assert_eq!(FOO.get(), 1);
57/// FOO.set(2);
58///
59/// // each thread starts out with the initial value of 1
60/// let t = thread::spawn(move || {
61///     assert_eq!(FOO.get(), 1);
62///     FOO.set(3);
63/// });
64///
65/// // wait for the thread to complete and bail out on panic
66/// t.join().unwrap();
67///
68/// // we retain our original value of 2 despite the child thread
69/// assert_eq!(FOO.get(), 2);
70/// ```
71///
72/// # Platform-specific behavior
73///
74/// Note that a "best effort" is made to ensure that destructors for types
75/// stored in thread local storage are run, but not all platforms can guarantee
76/// that destructors will be run for all types in thread local storage. For
77/// example, there are a number of known caveats where destructors are not run:
78///
79/// 1. On Unix systems when pthread-based TLS is being used, destructors will
80///    not be run for TLS values on the main thread when it exits. Note that the
81///    application will exit immediately after the main thread exits as well.
82/// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
83///    during destruction. Some platforms ensure that this cannot happen
84///    infinitely by preventing re-initialization of any slot that has been
85///    destroyed, but not all platforms have this guard. Those platforms that do
86///    not guard typically have a synthetic limit after which point no more
87///    destructors are run.
88/// 3. When the process exits on Windows systems, TLS destructors may only be
89///    run on the thread that causes the process to exit. This is because the
90///    other threads may be forcibly terminated.
91///
92/// ## Synchronization in thread-local destructors
93///
94/// On Windows, synchronization operations (such as [`JoinHandle::join`]) in
95/// thread local destructors are prone to deadlocks and so should be avoided.
96/// This is because the [loader lock] is held while a destructor is run. The
97/// lock is acquired whenever a thread starts or exits or when a DLL is loaded
98/// or unloaded. Therefore these events are blocked for as long as a thread
99/// local destructor is running.
100///
101/// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
102/// [`JoinHandle::join`]: crate::thread::JoinHandle::join
103/// [`with`]: LocalKey::with
104#[cfg_attr(not(test), rustc_diagnostic_item = "LocalKey")]
105#[stable(feature = "rust1", since = "1.0.0")]
106pub struct LocalKey<T: 'static> {
107    // This outer `LocalKey<T>` type is what's going to be stored in statics,
108    // but actual data inside will sometimes be tagged with #[thread_local].
109    // It's not valid for a true static to reference a #[thread_local] static,
110    // so we get around that by exposing an accessor through a layer of function
111    // indirection (this thunk).
112    //
113    // Note that the thunk is itself unsafe because the returned lifetime of the
114    // slot where data lives, `'static`, is not actually valid. The lifetime
115    // here is actually slightly shorter than the currently running thread!
116    //
117    // Although this is an extra layer of indirection, it should in theory be
118    // trivially devirtualizable by LLVM because the value of `inner` never
119    // changes and the constant should be readonly within a crate. This mainly
120    // only runs into problems when TLS statics are exported across crates.
121    inner: fn(Option<&mut Option<T>>) -> *const T,
122}
123
124#[stable(feature = "std_debug", since = "1.16.0")]
125impl<T: 'static> fmt::Debug for LocalKey<T> {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.debug_struct("LocalKey").finish_non_exhaustive()
128    }
129}
130
131/// Declare a new thread local storage key of type [`std::thread::LocalKey`].
132///
133/// # Syntax
134///
135/// The macro wraps any number of static declarations and makes them thread local.
136/// Publicity and attributes for each static are allowed. Example:
137///
138/// ```
139/// use std::cell::{Cell, RefCell};
140///
141/// thread_local! {
142///     pub static FOO: Cell<u32> = const { Cell::new(1) };
143///
144///     static BAR: RefCell<Vec<f32>> = RefCell::new(vec![1.0, 2.0]);
145/// }
146///
147/// assert_eq!(FOO.get(), 1);
148/// BAR.with_borrow(|v| assert_eq!(v[1], 2.0));
149/// ```
150///
151/// Note that only shared references (`&T`) to the inner data may be obtained, so a
152/// type such as [`Cell`] or [`RefCell`] is typically used to allow mutating access.
153///
154/// This macro supports a special `const {}` syntax that can be used
155/// when the initialization expression can be evaluated as a constant.
156/// This can enable a more efficient thread local implementation that
157/// can avoid lazy initialization. For types that do not
158/// [need to be dropped][crate::mem::needs_drop], this can enable an
159/// even more efficient implementation that does not need to
160/// track any additional state.
161///
162/// ```
163/// use std::cell::RefCell;
164///
165/// thread_local! {
166///     pub static FOO: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
167/// }
168///
169/// FOO.with_borrow(|v| assert_eq!(v.len(), 0));
170/// ```
171///
172/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
173/// information.
174///
175/// [`std::thread::LocalKey`]: crate::thread::LocalKey
176#[macro_export]
177#[stable(feature = "rust1", since = "1.0.0")]
178#[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
179#[allow_internal_unstable(thread_local_internals)]
180macro_rules! thread_local {
181    // empty (base case for the recursion)
182    () => {};
183
184    ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const $init:block; $($rest:tt)*) => (
185        $crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
186        $crate::thread_local!($($rest)*);
187    );
188
189    ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const $init:block) => (
190        $crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
191    );
192
193    // process multiple declarations
194    ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
195        $crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
196        $crate::thread_local!($($rest)*);
197    );
198
199    // handle a single declaration
200    ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
201        $crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
202    );
203}
204
205/// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
206#[stable(feature = "thread_local_try_with", since = "1.26.0")]
207#[non_exhaustive]
208#[derive(Clone, Copy, Eq, PartialEq)]
209pub struct AccessError;
210
211#[stable(feature = "thread_local_try_with", since = "1.26.0")]
212impl fmt::Debug for AccessError {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        f.debug_struct("AccessError").finish()
215    }
216}
217
218#[stable(feature = "thread_local_try_with", since = "1.26.0")]
219impl fmt::Display for AccessError {
220    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221        fmt::Display::fmt("already destroyed", f)
222    }
223}
224
225#[stable(feature = "thread_local_try_with", since = "1.26.0")]
226impl Error for AccessError {}
227
228// This ensures the panicking code is outlined from `with` for `LocalKey`.
229#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
230#[track_caller]
231#[cold]
232fn panic_access_error(err: AccessError) -> ! {
233    panic!("cannot access a Thread Local Storage value during or after destruction: {err:?}")
234}
235
236impl<T: 'static> LocalKey<T> {
237    #[doc(hidden)]
238    #[unstable(
239        feature = "thread_local_internals",
240        reason = "recently added to create a key",
241        issue = "none"
242    )]
243    pub const unsafe fn new(inner: fn(Option<&mut Option<T>>) -> *const T) -> LocalKey<T> {
244        LocalKey { inner }
245    }
246
247    /// Acquires a reference to the value in this TLS key.
248    ///
249    /// This will lazily initialize the value if this thread has not referenced
250    /// this key yet.
251    ///
252    /// # Panics
253    ///
254    /// This function will `panic!()` if the key currently has its
255    /// destructor running, and it **may** panic if the destructor has
256    /// previously been run for this thread.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// thread_local! {
262    ///     pub static STATIC: String = String::from("I am");
263    /// }
264    ///
265    /// assert_eq!(
266    ///     STATIC.with(|original_value| format!("{original_value} initialized")),
267    ///     "I am initialized",
268    /// );
269    /// ```
270    #[stable(feature = "rust1", since = "1.0.0")]
271    pub fn with<F, R>(&'static self, f: F) -> R
272    where
273        F: FnOnce(&T) -> R,
274    {
275        match self.try_with(f) {
276            Ok(r) => r,
277            Err(err) => panic_access_error(err),
278        }
279    }
280
281    /// Acquires a reference to the value in this TLS key.
282    ///
283    /// This will lazily initialize the value if this thread has not referenced
284    /// this key yet. If the key has been destroyed (which may happen if this is called
285    /// in a destructor), this function will return an [`AccessError`].
286    ///
287    /// # Panics
288    ///
289    /// This function will still `panic!()` if the key is uninitialized and the
290    /// key's initializer panics.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// thread_local! {
296    ///     pub static STATIC: String = String::from("I am");
297    /// }
298    ///
299    /// assert_eq!(
300    ///     STATIC.try_with(|original_value| format!("{original_value} initialized")),
301    ///     Ok(String::from("I am initialized")),
302    /// );
303    /// ```
304    #[stable(feature = "thread_local_try_with", since = "1.26.0")]
305    #[inline]
306    pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
307    where
308        F: FnOnce(&T) -> R,
309    {
310        let thread_local = unsafe { (self.inner)(None).as_ref().ok_or(AccessError)? };
311        Ok(f(thread_local))
312    }
313
314    /// Acquires a reference to the value in this TLS key, initializing it with
315    /// `init` if it wasn't already initialized on this thread.
316    ///
317    /// If `init` was used to initialize the thread local variable, `None` is
318    /// passed as the first argument to `f`. If it was already initialized,
319    /// `Some(init)` is passed to `f`.
320    ///
321    /// # Panics
322    ///
323    /// This function will panic if the key currently has its destructor
324    /// running, and it **may** panic if the destructor has previously been run
325    /// for this thread.
326    fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
327    where
328        F: FnOnce(Option<T>, &T) -> R,
329    {
330        let mut init = Some(init);
331
332        let reference = unsafe {
333            match (self.inner)(Some(&mut init)).as_ref() {
334                Some(r) => r,
335                None => panic_access_error(AccessError),
336            }
337        };
338
339        f(init, reference)
340    }
341}
342
343impl<T: 'static> LocalKey<Cell<T>> {
344    /// Sets or initializes the contained value.
345    ///
346    /// Unlike the other methods, this will *not* run the lazy initializer of
347    /// the thread local. Instead, it will be directly initialized with the
348    /// given value if it wasn't initialized yet.
349    ///
350    /// # Panics
351    ///
352    /// Panics if the key currently has its destructor running,
353    /// and it **may** panic if the destructor has previously been run for this thread.
354    ///
355    /// # Examples
356    ///
357    /// ```
358    /// use std::cell::Cell;
359    ///
360    /// thread_local! {
361    ///     static X: Cell<i32> = panic!("!");
362    /// }
363    ///
364    /// // Calling X.get() here would result in a panic.
365    ///
366    /// X.set(123); // But X.set() is fine, as it skips the initializer above.
367    ///
368    /// assert_eq!(X.get(), 123);
369    /// ```
370    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
371    pub fn set(&'static self, value: T) {
372        self.initialize_with(Cell::new(value), |value, cell| {
373            if let Some(value) = value {
374                // The cell was already initialized, so `value` wasn't used to
375                // initialize it. So we overwrite the current value with the
376                // new one instead.
377                cell.set(value.into_inner());
378            }
379        });
380    }
381
382    /// Returns a copy of the contained value.
383    ///
384    /// This will lazily initialize the value if this thread has not referenced
385    /// this key yet.
386    ///
387    /// # Panics
388    ///
389    /// Panics if the key currently has its destructor running,
390    /// and it **may** panic if the destructor has previously been run for this thread.
391    ///
392    /// # Examples
393    ///
394    /// ```
395    /// use std::cell::Cell;
396    ///
397    /// thread_local! {
398    ///     static X: Cell<i32> = const { Cell::new(1) };
399    /// }
400    ///
401    /// assert_eq!(X.get(), 1);
402    /// ```
403    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
404    pub fn get(&'static self) -> T
405    where
406        T: Copy,
407    {
408        self.with(Cell::get)
409    }
410
411    /// Takes the contained value, leaving `Default::default()` in its place.
412    ///
413    /// This will lazily initialize the value if this thread has not referenced
414    /// this key yet.
415    ///
416    /// # Panics
417    ///
418    /// Panics if the key currently has its destructor running,
419    /// and it **may** panic if the destructor has previously been run for this thread.
420    ///
421    /// # Examples
422    ///
423    /// ```
424    /// use std::cell::Cell;
425    ///
426    /// thread_local! {
427    ///     static X: Cell<Option<i32>> = const { Cell::new(Some(1)) };
428    /// }
429    ///
430    /// assert_eq!(X.take(), Some(1));
431    /// assert_eq!(X.take(), None);
432    /// ```
433    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
434    pub fn take(&'static self) -> T
435    where
436        T: Default,
437    {
438        self.with(Cell::take)
439    }
440
441    /// Replaces the contained value, returning the old value.
442    ///
443    /// This will lazily initialize the value if this thread has not referenced
444    /// this key yet.
445    ///
446    /// # Panics
447    ///
448    /// Panics if the key currently has its destructor running,
449    /// and it **may** panic if the destructor has previously been run for this thread.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// use std::cell::Cell;
455    ///
456    /// thread_local! {
457    ///     static X: Cell<i32> = const { Cell::new(1) };
458    /// }
459    ///
460    /// assert_eq!(X.replace(2), 1);
461    /// assert_eq!(X.replace(3), 2);
462    /// ```
463    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
464    #[rustc_confusables("swap")]
465    pub fn replace(&'static self, value: T) -> T {
466        self.with(|cell| cell.replace(value))
467    }
468}
469
470impl<T: 'static> LocalKey<RefCell<T>> {
471    /// Acquires a reference to the contained value.
472    ///
473    /// This will lazily initialize the value if this thread has not referenced
474    /// this key yet.
475    ///
476    /// # Panics
477    ///
478    /// Panics if the value is currently mutably borrowed.
479    ///
480    /// Panics if the key currently has its destructor running,
481    /// and it **may** panic if the destructor has previously been run for this thread.
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// use std::cell::RefCell;
487    ///
488    /// thread_local! {
489    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
490    /// }
491    ///
492    /// X.with_borrow(|v| assert!(v.is_empty()));
493    /// ```
494    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
495    pub fn with_borrow<F, R>(&'static self, f: F) -> R
496    where
497        F: FnOnce(&T) -> R,
498    {
499        self.with(|cell| f(&cell.borrow()))
500    }
501
502    /// Acquires a mutable reference to the contained value.
503    ///
504    /// This will lazily initialize the value if this thread has not referenced
505    /// this key yet.
506    ///
507    /// # Panics
508    ///
509    /// Panics if the value is currently borrowed.
510    ///
511    /// Panics if the key currently has its destructor running,
512    /// and it **may** panic if the destructor has previously been run for this thread.
513    ///
514    /// # Examples
515    ///
516    /// ```
517    /// use std::cell::RefCell;
518    ///
519    /// thread_local! {
520    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
521    /// }
522    ///
523    /// X.with_borrow_mut(|v| v.push(1));
524    ///
525    /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
526    /// ```
527    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
528    pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
529    where
530        F: FnOnce(&mut T) -> R,
531    {
532        self.with(|cell| f(&mut cell.borrow_mut()))
533    }
534
535    /// Sets or initializes the contained value.
536    ///
537    /// Unlike the other methods, this will *not* run the lazy initializer of
538    /// the thread local. Instead, it will be directly initialized with the
539    /// given value if it wasn't initialized yet.
540    ///
541    /// # Panics
542    ///
543    /// Panics if the value is currently borrowed.
544    ///
545    /// Panics if the key currently has its destructor running,
546    /// and it **may** panic if the destructor has previously been run for this thread.
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// use std::cell::RefCell;
552    ///
553    /// thread_local! {
554    ///     static X: RefCell<Vec<i32>> = panic!("!");
555    /// }
556    ///
557    /// // Calling X.with() here would result in a panic.
558    ///
559    /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
560    ///
561    /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
562    /// ```
563    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
564    pub fn set(&'static self, value: T) {
565        self.initialize_with(RefCell::new(value), |value, cell| {
566            if let Some(value) = value {
567                // The cell was already initialized, so `value` wasn't used to
568                // initialize it. So we overwrite the current value with the
569                // new one instead.
570                *cell.borrow_mut() = value.into_inner();
571            }
572        });
573    }
574
575    /// Takes the contained value, leaving `Default::default()` in its place.
576    ///
577    /// This will lazily initialize the value if this thread has not referenced
578    /// this key yet.
579    ///
580    /// # Panics
581    ///
582    /// Panics if the value is currently borrowed.
583    ///
584    /// Panics if the key currently has its destructor running,
585    /// and it **may** panic if the destructor has previously been run for this thread.
586    ///
587    /// # Examples
588    ///
589    /// ```
590    /// use std::cell::RefCell;
591    ///
592    /// thread_local! {
593    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
594    /// }
595    ///
596    /// X.with_borrow_mut(|v| v.push(1));
597    ///
598    /// let a = X.take();
599    ///
600    /// assert_eq!(a, vec![1]);
601    ///
602    /// X.with_borrow(|v| assert!(v.is_empty()));
603    /// ```
604    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
605    pub fn take(&'static self) -> T
606    where
607        T: Default,
608    {
609        self.with(RefCell::take)
610    }
611
612    /// Replaces the contained value, returning the old value.
613    ///
614    /// # Panics
615    ///
616    /// Panics if the value is currently borrowed.
617    ///
618    /// Panics if the key currently has its destructor running,
619    /// and it **may** panic if the destructor has previously been run for this thread.
620    ///
621    /// # Examples
622    ///
623    /// ```
624    /// use std::cell::RefCell;
625    ///
626    /// thread_local! {
627    ///     static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
628    /// }
629    ///
630    /// let prev = X.replace(vec![1, 2, 3]);
631    /// assert!(prev.is_empty());
632    ///
633    /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
634    /// ```
635    #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
636    #[rustc_confusables("swap")]
637    pub fn replace(&'static self, value: T) -> T {
638        self.with(|cell| cell.replace(value))
639    }
640}