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::RefCell;
57/// use std::thread;
58///
59/// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
60///
61/// FOO.with_borrow(|v| assert_eq!(*v, 1));
62/// FOO.with_borrow_mut(|v| *v = 2);
63///
64/// // each thread starts out with the initial value of 1
65/// let t = thread::spawn(move|| {
66/// FOO.with_borrow(|v| assert_eq!(*v, 1));
67/// FOO.with_borrow_mut(|v| *v = 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/// FOO.with_borrow(|v| assert_eq!(*v, 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::RefCell;
145/// thread_local! {
146/// pub static FOO: RefCell<u32> = RefCell::new(1);
147///
148/// static BAR: RefCell<f32> = RefCell::new(1.0);
149/// }
150///
151/// FOO.with_borrow(|v| assert_eq!(*v, 1));
152/// BAR.with_borrow(|v| assert_eq!(*v, 1.0));
153/// ```
154///
155/// Note that only shared references (`&T`) to the inner data may be obtained, so a
156/// type such as [`Cell`] or [`RefCell`] is typically used to allow mutating access.
157///
158/// This macro supports a special `const {}` syntax that can be used
159/// when the initialization expression can be evaluated as a constant.
160/// This can enable a more efficient thread local implementation that
161/// can avoid lazy initialization. For types that do not
162/// [need to be dropped][crate::mem::needs_drop], this can enable an
163/// even more efficient implementation that does not need to
164/// track any additional state.
165///
166/// ```
167/// use std::cell::Cell;
168/// thread_local! {
169/// pub static FOO: Cell<u32> = const { Cell::new(1) };
170/// }
171///
172/// assert_eq!(FOO.get(), 1);
173/// ```
174///
175/// See [`LocalKey` documentation][`std::thread::LocalKey`] for more
176/// information.
177///
178/// [`std::thread::LocalKey`]: crate::thread::LocalKey
179#[macro_export]
180#[stable(feature = "rust1", since = "1.0.0")]
181#[cfg_attr(not(test), rustc_diagnostic_item = "thread_local_macro")]
182#[allow_internal_unstable(thread_local_internals)]
183// FIXME: Use `SyncUnsafeCell` instead of allowing `static_mut_refs` lint
184#[cfg_attr(not(bootstrap), allow(static_mut_refs))]
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 unsafe {
285 let thread_local = (self.inner)(None).ok_or(AccessError)?;
286 Ok(f(thread_local))
287 }
288 }
289
290 /// Acquires a reference to the value in this TLS key, initializing it with
291 /// `init` if it wasn't already initialized on this thread.
292 ///
293 /// If `init` was used to initialize the thread local variable, `None` is
294 /// passed as the first argument to `f`. If it was already initialized,
295 /// `Some(init)` is passed to `f`.
296 ///
297 /// # Panics
298 ///
299 /// This function will panic if the key currently has its destructor
300 /// running, and it **may** panic if the destructor has previously been run
301 /// for this thread.
302 fn initialize_with<F, R>(&'static self, init: T, f: F) -> R
303 where
304 F: FnOnce(Option<T>, &T) -> R,
305 {
306 unsafe {
307 let mut init = Some(init);
308 let reference = (self.inner)(Some(&mut init)).expect(
309 "cannot access a Thread Local Storage value \
310 during or after destruction",
311 );
312 f(init, reference)
313 }
314 }
315}
316
317impl<T: 'static> LocalKey<Cell<T>> {
318 /// Sets or initializes the contained value.
319 ///
320 /// Unlike the other methods, this will *not* run the lazy initializer of
321 /// the thread local. Instead, it will be directly initialized with the
322 /// given value if it wasn't initialized yet.
323 ///
324 /// # Panics
325 ///
326 /// Panics if the key currently has its destructor running,
327 /// and it **may** panic if the destructor has previously been run for this thread.
328 ///
329 /// # Examples
330 ///
331 /// ```
332 /// use std::cell::Cell;
333 ///
334 /// thread_local! {
335 /// static X: Cell<i32> = panic!("!");
336 /// }
337 ///
338 /// // Calling X.get() here would result in a panic.
339 ///
340 /// X.set(123); // But X.set() is fine, as it skips the initializer above.
341 ///
342 /// assert_eq!(X.get(), 123);
343 /// ```
344 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
345 pub fn set(&'static self, value: T) {
346 self.initialize_with(Cell::new(value), |value, cell| {
347 if let Some(value) = value {
348 // The cell was already initialized, so `value` wasn't used to
349 // initialize it. So we overwrite the current value with the
350 // new one instead.
351 cell.set(value.into_inner());
352 }
353 });
354 }
355
356 /// Returns a copy of the contained value.
357 ///
358 /// This will lazily initialize the value if this thread has not referenced
359 /// this key yet.
360 ///
361 /// # Panics
362 ///
363 /// Panics if the key currently has its destructor running,
364 /// and it **may** panic if the destructor has previously been run for this thread.
365 ///
366 /// # Examples
367 ///
368 /// ```
369 /// use std::cell::Cell;
370 ///
371 /// thread_local! {
372 /// static X: Cell<i32> = Cell::new(1);
373 /// }
374 ///
375 /// assert_eq!(X.get(), 1);
376 /// ```
377 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
378 pub fn get(&'static self) -> T
379 where
380 T: Copy,
381 {
382 self.with(|cell| cell.get())
383 }
384
385 /// Takes the contained value, leaving `Default::default()` in its place.
386 ///
387 /// This will lazily initialize the value if this thread has not referenced
388 /// this key yet.
389 ///
390 /// # Panics
391 ///
392 /// Panics if the key currently has its destructor running,
393 /// and it **may** panic if the destructor has previously been run for this thread.
394 ///
395 /// # Examples
396 ///
397 /// ```
398 /// use std::cell::Cell;
399 ///
400 /// thread_local! {
401 /// static X: Cell<Option<i32>> = Cell::new(Some(1));
402 /// }
403 ///
404 /// assert_eq!(X.take(), Some(1));
405 /// assert_eq!(X.take(), None);
406 /// ```
407 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
408 pub fn take(&'static self) -> T
409 where
410 T: Default,
411 {
412 self.with(|cell| cell.take())
413 }
414
415 /// Replaces the contained value, returning the old value.
416 ///
417 /// This will lazily initialize the value if this thread has not referenced
418 /// this key yet.
419 ///
420 /// # Panics
421 ///
422 /// Panics if the key currently has its destructor running,
423 /// and it **may** panic if the destructor has previously been run for this thread.
424 ///
425 /// # Examples
426 ///
427 /// ```
428 /// use std::cell::Cell;
429 ///
430 /// thread_local! {
431 /// static X: Cell<i32> = Cell::new(1);
432 /// }
433 ///
434 /// assert_eq!(X.replace(2), 1);
435 /// assert_eq!(X.replace(3), 2);
436 /// ```
437 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
438 pub fn replace(&'static self, value: T) -> T {
439 self.with(|cell| cell.replace(value))
440 }
441}
442
443impl<T: 'static> LocalKey<RefCell<T>> {
444 /// Acquires a reference to the contained value.
445 ///
446 /// This will lazily initialize the value if this thread has not referenced
447 /// this key yet.
448 ///
449 /// # Panics
450 ///
451 /// Panics if the value is currently mutably borrowed.
452 ///
453 /// Panics if the key currently has its destructor running,
454 /// and it **may** panic if the destructor has previously been run for this thread.
455 ///
456 /// # Example
457 ///
458 /// ```
459 /// use std::cell::RefCell;
460 ///
461 /// thread_local! {
462 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
463 /// }
464 ///
465 /// X.with_borrow(|v| assert!(v.is_empty()));
466 /// ```
467 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
468 pub fn with_borrow<F, R>(&'static self, f: F) -> R
469 where
470 F: FnOnce(&T) -> R,
471 {
472 self.with(|cell| f(&cell.borrow()))
473 }
474
475 /// Acquires a mutable reference to the contained value.
476 ///
477 /// This will lazily initialize the value if this thread has not referenced
478 /// this key yet.
479 ///
480 /// # Panics
481 ///
482 /// Panics if the value is currently borrowed.
483 ///
484 /// Panics if the key currently has its destructor running,
485 /// and it **may** panic if the destructor has previously been run for this thread.
486 ///
487 /// # Example
488 ///
489 /// ```
490 /// use std::cell::RefCell;
491 ///
492 /// thread_local! {
493 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
494 /// }
495 ///
496 /// X.with_borrow_mut(|v| v.push(1));
497 ///
498 /// X.with_borrow(|v| assert_eq!(*v, vec![1]));
499 /// ```
500 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
501 pub fn with_borrow_mut<F, R>(&'static self, f: F) -> R
502 where
503 F: FnOnce(&mut T) -> R,
504 {
505 self.with(|cell| f(&mut cell.borrow_mut()))
506 }
507
508 /// Sets or initializes the contained value.
509 ///
510 /// Unlike the other methods, this will *not* run the lazy initializer of
511 /// the thread local. Instead, it will be directly initialized with the
512 /// given value if it wasn't initialized yet.
513 ///
514 /// # Panics
515 ///
516 /// Panics if the value is currently borrowed.
517 ///
518 /// Panics if the key currently has its destructor running,
519 /// and it **may** panic if the destructor has previously been run for this thread.
520 ///
521 /// # Examples
522 ///
523 /// ```
524 /// use std::cell::RefCell;
525 ///
526 /// thread_local! {
527 /// static X: RefCell<Vec<i32>> = panic!("!");
528 /// }
529 ///
530 /// // Calling X.with() here would result in a panic.
531 ///
532 /// X.set(vec![1, 2, 3]); // But X.set() is fine, as it skips the initializer above.
533 ///
534 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
535 /// ```
536 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
537 pub fn set(&'static self, value: T) {
538 self.initialize_with(RefCell::new(value), |value, cell| {
539 if let Some(value) = value {
540 // The cell was already initialized, so `value` wasn't used to
541 // initialize it. So we overwrite the current value with the
542 // new one instead.
543 *cell.borrow_mut() = value.into_inner();
544 }
545 });
546 }
547
548 /// Takes the contained value, leaving `Default::default()` in its place.
549 ///
550 /// This will lazily initialize the value if this thread has not referenced
551 /// this key yet.
552 ///
553 /// # Panics
554 ///
555 /// Panics if the value is currently borrowed.
556 ///
557 /// Panics if the key currently has its destructor running,
558 /// and it **may** panic if the destructor has previously been run for this thread.
559 ///
560 /// # Examples
561 ///
562 /// ```
563 /// use std::cell::RefCell;
564 ///
565 /// thread_local! {
566 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
567 /// }
568 ///
569 /// X.with_borrow_mut(|v| v.push(1));
570 ///
571 /// let a = X.take();
572 ///
573 /// assert_eq!(a, vec![1]);
574 ///
575 /// X.with_borrow(|v| assert!(v.is_empty()));
576 /// ```
577 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
578 pub fn take(&'static self) -> T
579 where
580 T: Default,
581 {
582 self.with(|cell| cell.take())
583 }
584
585 /// Replaces the contained value, returning the old value.
586 ///
587 /// # Panics
588 ///
589 /// Panics if the value is currently borrowed.
590 ///
591 /// Panics if the key currently has its destructor running,
592 /// and it **may** panic if the destructor has previously been run for this thread.
593 ///
594 /// # Examples
595 ///
596 /// ```
597 /// use std::cell::RefCell;
598 ///
599 /// thread_local! {
600 /// static X: RefCell<Vec<i32>> = RefCell::new(Vec::new());
601 /// }
602 ///
603 /// let prev = X.replace(vec![1, 2, 3]);
604 /// assert!(prev.is_empty());
605 ///
606 /// X.with_borrow(|v| assert_eq!(*v, vec![1, 2, 3]));
607 /// ```
608 #[stable(feature = "local_key_cell_methods", since = "1.73.0")]
609 pub fn replace(&'static self, value: T) -> T {
610 self.with(|cell| cell.replace(value))
611 }
612}
613