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