]>
git.proxmox.com Git - rustc.git/blob - library/std/src/thread/local.rs
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
22 /// outlive the current thread 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. Using a
33 /// `LocalKey` in this way may cause panics, aborts or infinite recursion on
34 /// 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);
137 /// static BAR: RefCell<f32> = RefCell::new(1.0);
140 /// FOO.with(|foo| assert_eq!(*foo.borrow(), 1));
141 /// BAR.with(|bar| assert_eq!(*bar.borrow(), 1.0));
144 /// This macro supports a special `const {}` syntax that can be used
145 /// when the initialization expression can be evaluated as a constant.
146 /// This can enable a more efficient thread local implementation that
147 /// can avoid lazy initialization. For types that do not
148 /// [need to be dropped][crate::mem::needs_drop], this can enable an
149 /// even more efficient implementation that does not need to
150 /// track any additional state.
153 /// use std::cell::Cell;
155 /// pub static FOO: Cell<u32> = const { Cell::new(1) };
158 /// FOO.with(|foo| assert_eq!(foo.get(), 1));
161 /// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
164 /// [`std::thread::LocalKey`]: crate::thread::LocalKey
166 #[stable(feature = "rust1", since = "1.0.0")]
167 #[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
168 #[allow_internal_unstable(thread_local_internals)]
169 macro_rules
! thread_local
{
170 // empty (base case for the recursion)
173 ($
(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
174 $
crate::thread
::local_impl
::thread_local_inner
!($
(#[$attr])* $vis $name, $t, const $init);
175 $
crate::thread_local
!($
($rest
)*);
178 ($
(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => (
179 $
crate::thread
::local_impl
::thread_local_inner
!($
(#[$attr])* $vis $name, $t, const $init);
182 // process multiple declarations
183 ($
(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
184 $
crate::thread
::local_impl
::thread_local_inner
!($
(#[$attr])* $vis $name, $t, $init);
185 $
crate::thread_local
!($
($rest
)*);
188 // handle a single declaration
189 ($
(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
190 $
crate::thread
::local_impl
::thread_local_inner
!($
(#[$attr])* $vis $name, $t, $init);
194 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
195 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
197 #[derive(Clone, Copy, Eq, PartialEq)]
198 pub struct AccessError
;
200 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
201 impl fmt
::Debug
for AccessError
{
202 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
203 f
.debug_struct("AccessError").finish()
207 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
208 impl fmt
::Display
for AccessError
{
209 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
210 fmt
::Display
::fmt("already destroyed", f
)
214 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
215 impl Error
for AccessError {}
217 impl<T
: '
static> LocalKey
<T
> {
220 feature
= "thread_local_internals",
221 reason
= "recently added to create a key",
224 #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
225 pub const unsafe fn new(
226 inner
: unsafe fn(Option
<&mut Option
<T
>>) -> Option
<&'
static T
>,
231 /// Acquires a reference to the value in this TLS key.
233 /// This will lazily initialize the value if this thread has not referenced
238 /// This function will `panic!()` if the key currently has its
239 /// destructor running, and it **may** panic if the destructor has
240 /// previously been run for this thread.
241 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn with
<F
, R
>(&'
static self, f
: F
) -> R
246 self.try_with(f
).expect(
247 "cannot access a Thread Local Storage value \
248 during or after destruction",
252 /// Acquires a reference to the value in this TLS key.
254 /// This will lazily initialize the value if this thread has not referenced
255 /// this key yet. If the key has been destroyed (which may happen if this is called
256 /// in a destructor), this function will return an [`AccessError`].
260 /// This function will still `panic!()` if the key is uninitialized and the
261 /// key's initializer panics.
262 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
264 pub fn try_with
<F
, R
>(&'
static self, f
: F
) -> Result
<R
, AccessError
>
269 let thread_local
= (self.inner
)(None
).ok_or(AccessError
)?
;
274 /// Acquires a reference to the value in this TLS key, initializing it with
275 /// `init` if it wasn't already initialized on this thread.
277 /// If `init` was used to initialize the thread local variable, `None` is
278 /// passed as the first argument to `f`. If it was already initialized,
279 /// `Some(init)` is passed to `f`.
283 /// This function will panic if the key currently has its destructor
284 /// running, and it **may** panic if the destructor has previously been run
286 fn initialize_with
<F
, R
>(&'
static self, init
: T
, f
: F
) -> R
288 F
: FnOnce(Option
<T
>, &T
) -> R
,
291 let mut init
= Some(init
);
292 let reference
= (self.inner
)(Some(&mut init
)).expect(
293 "cannot access a Thread Local Storage value \
294 during or after destruction",
301 impl<T
: '
static> LocalKey
<Cell
<T
>> {
302 /// Sets or initializes the contained value.
304 /// Unlike the other methods, this will *not* run the lazy initializer of
305 /// the thread local. Instead, it will be directly initialized with the
306 /// given value if it wasn't initialized yet.
310 /// Panics if the key currently has its destructor running,
311 /// and it **may** panic if the destructor has previously been run for this thread.
316 /// use std::cell::Cell;
319 /// static X: Cell<i32> = panic!("!");
322 /// // Calling X.get() here would result in a panic.
324 /// X.set(123); // But X.set() is fine, as it skips the initializer above.
326 /// assert_eq!(X.get(), 123);
328 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
329 pub fn set(&'
static self, value
: T
) {
330 self.initialize_with(Cell
::new(value
), |value
, cell
| {
331 if let Some(value
) = value
{
332 // The cell was already initialized, so `value` wasn't used to
333 // initialize it. So we overwrite the current value with the
335 cell
.set(value
.into_inner());
340 /// Returns a copy of the contained value.
342 /// This will lazily initialize the value if this thread has not referenced
347 /// Panics if the key currently has its destructor running,
348 /// and it **may** panic if the destructor has previously been run for this thread.
353 /// use std::cell::Cell;
356 /// static X: Cell<i32> = Cell::new(1);
359 /// assert_eq!(X.get(), 1);
361 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
362 pub fn get(&'
static self) -> T
366 self.with(|cell
| cell
.get())
369 /// Takes the contained value, leaving `Default::default()` in its place.
371 /// This will lazily initialize the value if this thread has not referenced
376 /// Panics if the key currently has its destructor running,
377 /// and it **may** panic if the destructor has previously been run for this thread.
382 /// use std::cell::Cell;
385 /// static X: Cell<Option<i32>> = Cell::new(Some(1));
388 /// assert_eq!(X.take(), Some(1));
389 /// assert_eq!(X.take(), None);
391 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
392 pub fn take(&'
static self) -> T
396 self.with(|cell
| cell
.take())
399 /// Replaces the contained value, returning the old value.
401 /// This will lazily initialize the value if this thread has not referenced
406 /// Panics if the key currently has its destructor running,
407 /// and it **may** panic if the destructor has previously been run for this thread.
412 /// use std::cell::Cell;
415 /// static X: Cell<i32> = Cell::new(1);
418 /// assert_eq!(X.replace(2), 1);
419 /// assert_eq!(X.replace(3), 2);
421 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
422 pub fn replace(&'
static self, value
: T
) -> T
{
423 self.with(|cell
| cell
.replace(value
))
427 impl<T
: '
static> LocalKey
<RefCell
<T
>> {
428 /// Acquires a reference to the contained value.
430 /// This will lazily initialize the value if this thread has not referenced
435 /// Panics if the value is currently mutably borrowed.
437 /// Panics if the key currently has its destructor running,
438 /// and it **may** panic if the destructor has previously been run for this thread.
443 /// use std::cell::RefCell;
446 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
449 /// X.with_borrow(|v| assert!(v.is_empty()));
451 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
452 pub fn with_borrow
<F
, R
>(&'
static self, f
: F
) -> R
456 self.with(|cell
| f(&cell
.borrow()))
459 /// Acquires a mutable reference to the contained value.
461 /// This will lazily initialize the value if this thread has not referenced
466 /// Panics if the value is currently borrowed.
468 /// Panics if the key currently has its destructor running,
469 /// and it **may** panic if the destructor has previously been run for this thread.
474 /// use std::cell::RefCell;
477 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
480 /// X.with_borrow_mut(|v| v.push(1));
482 /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
484 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
485 pub fn with_borrow_mut
<F
, R
>(&'
static self, f
: F
) -> R
487 F
: FnOnce(&mut T
) -> R
,
489 self.with(|cell
| f(&mut cell
.borrow_mut()))
492 /// Sets or initializes the contained value.
494 /// Unlike the other methods, this will *not* run the lazy initializer of
495 /// the thread local. Instead, it will be directly initialized with the
496 /// given value if it wasn't initialized yet.
500 /// Panics if the value is currently borrowed.
502 /// Panics if the key currently has its destructor running,
503 /// and it **may** panic if the destructor has previously been run for this thread.
508 /// use std::cell::RefCell;
511 /// static X: RefCell<Vec<i32>> = panic!("!");
514 /// // Calling X.with() here would result in a panic.
516 /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
518 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
520 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
521 pub fn set(&'
static self, value
: T
) {
522 self.initialize_with(RefCell
::new(value
), |value
, cell
| {
523 if let Some(value
) = value
{
524 // The cell was already initialized, so `value` wasn't used to
525 // initialize it. So we overwrite the current value with the
527 *cell
.borrow_mut() = value
.into_inner();
532 /// Takes the contained value, leaving `Default::default()` in its place.
534 /// This will lazily initialize the value if this thread has not referenced
539 /// Panics if the value is currently borrowed.
541 /// Panics if the key currently has its destructor running,
542 /// and it **may** panic if the destructor has previously been run for this thread.
547 /// use std::cell::RefCell;
550 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
553 /// X.with_borrow_mut(|v| v.push(1));
555 /// let a = X.take();
557 /// assert_eq!(a, vec![1]);
559 /// X.with_borrow(|v| assert!(v.is_empty()));
561 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
562 pub fn take(&'
static self) -> T
566 self.with(|cell
| cell
.take())
569 /// Replaces the contained value, returning the old value.
573 /// Panics if the value is currently borrowed.
575 /// Panics if the key currently has its destructor running,
576 /// and it **may** panic if the destructor has previously been run for this thread.
581 /// use std::cell::RefCell;
584 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
587 /// let prev = X.replace(vec![1, 2, 3]);
588 /// assert!(prev.is_empty());
590 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
592 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
593 pub fn replace(&'
static self, value
: T
) -> T
{
594 self.with(|cell
| cell
.replace(value
))