]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/local.rs
Rollup merge of #55391 - matthiaskrgr:bootstrap_cleanup, r=TimNN
[rust.git] / src / libstd / thread / local.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Thread local storage
12
13 #![unstable(feature = "thread_local_internals", issue = "0")]
14
15 use cell::UnsafeCell;
16 use fmt;
17 use hint;
18 use mem;
19
20 /// A thread local storage key which owns its contents.
21 ///
22 /// This key uses the fastest possible implementation available to it for the
23 /// target platform. It is instantiated with the [`thread_local!`] macro and the
24 /// primary method is the [`with`] method.
25 ///
26 /// The [`with`] method yields a reference to the contained value which cannot be
27 /// sent across threads or escape the given closure.
28 ///
29 /// # Initialization and Destruction
30 ///
31 /// Initialization is dynamically performed on the first call to [`with`]
32 /// within a thread, and values that implement [`Drop`] get destructed when a
33 /// thread exits. Some caveats apply, which are explained below.
34 ///
35 /// A `LocalKey`'s initializer cannot recursively depend on itself, and using
36 /// a `LocalKey` in this way will cause the initializer to infinitely recurse
37 /// on the first call to `with`.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// use std::cell::RefCell;
43 /// use std::thread;
44 ///
45 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
46 ///
47 /// FOO.with(|f| {
48 ///     assert_eq!(*f.borrow(), 1);
49 ///     *f.borrow_mut() = 2;
50 /// });
51 ///
52 /// // each thread starts out with the initial value of 1
53 /// thread::spawn(move|| {
54 ///     FOO.with(|f| {
55 ///         assert_eq!(*f.borrow(), 1);
56 ///         *f.borrow_mut() = 3;
57 ///     });
58 /// });
59 ///
60 /// // we retain our original value of 2 despite the child thread
61 /// FOO.with(|f| {
62 ///     assert_eq!(*f.borrow(), 2);
63 /// });
64 /// ```
65 ///
66 /// # Platform-specific behavior
67 ///
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:
72 ///
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. On macOS, initializing TLS during destruction of other TLS slots can
83 ///    sometimes cancel *all* destructors for the current thread, whether or not
84 ///    the slots have already had their destructors run or not.
85 ///
86 /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with
87 /// [`thread_local!`]: ../../std/macro.thread_local.html
88 /// [`Drop`]: ../../std/ops/trait.Drop.html
89 #[stable(feature = "rust1", since = "1.0.0")]
90 pub struct LocalKey<T: 'static> {
91     // This outer `LocalKey<T>` type is what's going to be stored in statics,
92     // but actual data inside will sometimes be tagged with #[thread_local].
93     // It's not valid for a true static to reference a #[thread_local] static,
94     // so we get around that by exposing an accessor through a layer of function
95     // indirection (this thunk).
96     //
97     // Note that the thunk is itself unsafe because the returned lifetime of the
98     // slot where data lives, `'static`, is not actually valid. The lifetime
99     // here is actually slightly shorter than the currently running thread!
100     //
101     // Although this is an extra layer of indirection, it should in theory be
102     // trivially devirtualizable by LLVM because the value of `inner` never
103     // changes and the constant should be readonly within a crate. This mainly
104     // only runs into problems when TLS statics are exported across crates.
105     inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
106
107     // initialization routine to invoke to create a value
108     init: fn() -> T,
109 }
110
111 #[stable(feature = "std_debug", since = "1.16.0")]
112 impl<T: 'static> fmt::Debug for LocalKey<T> {
113     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114         f.pad("LocalKey { .. }")
115     }
116 }
117
118 /// Declare a new thread local storage key of type [`std::thread::LocalKey`].
119 ///
120 /// # Syntax
121 ///
122 /// The macro wraps any number of static declarations and makes them thread local.
123 /// Publicity and attributes for each static are allowed. Example:
124 ///
125 /// ```
126 /// use std::cell::RefCell;
127 /// thread_local! {
128 ///     pub static FOO: RefCell<u32> = RefCell::new(1);
129 ///
130 ///     #[allow(unused)]
131 ///     static BAR: RefCell<f32> = RefCell::new(1.0);
132 /// }
133 /// # fn main() {}
134 /// ```
135 ///
136 /// See [LocalKey documentation][`std::thread::LocalKey`] for more
137 /// information.
138 ///
139 /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html
140 #[macro_export]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[allow_internal_unstable]
143 macro_rules! thread_local {
144     // empty (base case for the recursion)
145     () => {};
146
147     // process multiple declarations
148     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
149         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
150         $crate::thread_local!($($rest)*);
151     );
152
153     // handle a single declaration
154     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
155         $crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
156     );
157 }
158
159 #[doc(hidden)]
160 #[unstable(feature = "thread_local_internals",
161            reason = "should not be necessary",
162            issue = "0")]
163 #[macro_export]
164 #[allow_internal_unstable]
165 #[allow_internal_unsafe]
166 macro_rules! __thread_local_inner {
167     (@key $(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
168         {
169             #[inline]
170             fn __init() -> $t { $init }
171
172             unsafe fn __getit() -> $crate::option::Option<
173                 &'static $crate::cell::UnsafeCell<
174                     $crate::option::Option<$t>>>
175             {
176                 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
177                 static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
178                     $crate::thread::__StaticLocalKeyInner::new();
179
180                 #[thread_local]
181                 #[cfg(all(
182                     target_thread_local,
183                     not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
184                 ))]
185                 static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
186                     $crate::thread::__FastLocalKeyInner::new();
187
188                 #[cfg(all(
189                     not(target_thread_local),
190                     not(all(target_arch = "wasm32", not(target_feature = "atomics"))),
191                 ))]
192                 static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
193                     $crate::thread::__OsLocalKeyInner::new();
194
195                 __KEY.get()
196             }
197
198             unsafe {
199                 $crate::thread::LocalKey::new(__getit, __init)
200             }
201         }
202     };
203     ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => {
204         $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
205             $crate::__thread_local_inner!(@key $(#[$attr])* $vis $name, $t, $init);
206     }
207 }
208
209 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
210 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
211 pub struct AccessError {
212     _private: (),
213 }
214
215 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
216 impl fmt::Debug for AccessError {
217     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
218         f.debug_struct("AccessError").finish()
219     }
220 }
221
222 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
223 impl fmt::Display for AccessError {
224     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225         fmt::Display::fmt("already destroyed", f)
226     }
227 }
228
229 impl<T: 'static> LocalKey<T> {
230     #[doc(hidden)]
231     #[unstable(feature = "thread_local_internals",
232                reason = "recently added to create a key",
233                issue = "0")]
234     pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>,
235                             init: fn() -> T) -> LocalKey<T> {
236         LocalKey {
237             inner,
238             init,
239         }
240     }
241
242     /// Acquires a reference to the value in this TLS key.
243     ///
244     /// This will lazily initialize the value if this thread has not referenced
245     /// this key yet.
246     ///
247     /// # Panics
248     ///
249     /// This function will `panic!()` if the key currently has its
250     /// destructor running, and it **may** panic if the destructor has
251     /// previously been run for this thread.
252     #[stable(feature = "rust1", since = "1.0.0")]
253     pub fn with<F, R>(&'static self, f: F) -> R
254                       where F: FnOnce(&T) -> R {
255         self.try_with(f).expect("cannot access a TLS value during or \
256                                  after it is destroyed")
257     }
258
259     unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
260         // Execute the initialization up front, *then* move it into our slot,
261         // just in case initialization fails.
262         let value = (self.init)();
263         let ptr = slot.get();
264
265         // note that this can in theory just be `*ptr = Some(value)`, but due to
266         // the compiler will currently codegen that pattern with something like:
267         //
268         //      ptr::drop_in_place(ptr)
269         //      ptr::write(ptr, Some(value))
270         //
271         // Due to this pattern it's possible for the destructor of the value in
272         // `ptr` (e.g. if this is being recursively initialized) to re-access
273         // TLS, in which case there will be a `&` and `&mut` pointer to the same
274         // value (an aliasing violation). To avoid setting the "I'm running a
275         // destructor" flag we just use `mem::replace` which should sequence the
276         // operations a little differently and make this safe to call.
277         mem::replace(&mut *ptr, Some(value));
278
279         // After storing `Some` we want to get a reference to the contents of
280         // what we just stored. While we could use `unwrap` here and it should
281         // always work it empirically doesn't seem to always get optimized away,
282         // which means that using something like `try_with` can pull in
283         // panicking code and cause a large size bloat.
284         match *ptr {
285             Some(ref x) => x,
286             None => hint::unreachable_unchecked(),
287         }
288     }
289
290     /// Acquires a reference to the value in this TLS key.
291     ///
292     /// This will lazily initialize the value if this thread has not referenced
293     /// this key yet. If the key has been destroyed (which may happen if this is called
294     /// in a destructor), this function will return an [`AccessError`](struct.AccessError.html).
295     ///
296     /// # Panics
297     ///
298     /// This function will still `panic!()` if the key is uninitialized and the
299     /// key's initializer panics.
300     #[stable(feature = "thread_local_try_with", since = "1.26.0")]
301     pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
302     where
303         F: FnOnce(&T) -> R,
304     {
305         unsafe {
306             let slot = (self.inner)().ok_or(AccessError {
307                 _private: (),
308             })?;
309             Ok(f(match *slot.get() {
310                 Some(ref inner) => inner,
311                 None => self.init(slot),
312             }))
313         }
314     }
315 }
316
317 /// On some platforms like wasm32 there's no threads, so no need to generate
318 /// thread locals and we can instead just use plain statics!
319 #[doc(hidden)]
320 #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))]
321 pub mod statik {
322     use cell::UnsafeCell;
323     use fmt;
324
325     pub struct Key<T> {
326         inner: UnsafeCell<Option<T>>,
327     }
328
329     unsafe impl<T> ::marker::Sync for Key<T> { }
330
331     impl<T> fmt::Debug for Key<T> {
332         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333             f.pad("Key { .. }")
334         }
335     }
336
337     impl<T> Key<T> {
338         pub const fn new() -> Key<T> {
339             Key {
340                 inner: UnsafeCell::new(None),
341             }
342         }
343
344         pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
345             Some(&*(&self.inner as *const _))
346         }
347     }
348 }
349
350 #[doc(hidden)]
351 #[cfg(target_thread_local)]
352 pub mod fast {
353     use cell::{Cell, UnsafeCell};
354     use fmt;
355     use mem;
356     use ptr;
357     use sys::fast_thread_local::{register_dtor, requires_move_before_drop};
358
359     pub struct Key<T> {
360         inner: UnsafeCell<Option<T>>,
361
362         // Metadata to keep track of the state of the destructor. Remember that
363         // these variables are thread-local, not global.
364         dtor_registered: Cell<bool>,
365         dtor_running: Cell<bool>,
366     }
367
368     impl<T> fmt::Debug for Key<T> {
369         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
370             f.pad("Key { .. }")
371         }
372     }
373
374     impl<T> Key<T> {
375         pub const fn new() -> Key<T> {
376             Key {
377                 inner: UnsafeCell::new(None),
378                 dtor_registered: Cell::new(false),
379                 dtor_running: Cell::new(false)
380             }
381         }
382
383         pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> {
384             if mem::needs_drop::<T>() && self.dtor_running.get() {
385                 return None
386             }
387             self.register_dtor();
388             Some(&*(&self.inner as *const _))
389         }
390
391         unsafe fn register_dtor(&self) {
392             if !mem::needs_drop::<T>() || self.dtor_registered.get() {
393                 return
394             }
395
396             register_dtor(self as *const _ as *mut u8,
397                           destroy_value::<T>);
398             self.dtor_registered.set(true);
399         }
400     }
401
402     unsafe extern fn destroy_value<T>(ptr: *mut u8) {
403         let ptr = ptr as *mut Key<T>;
404         // Right before we run the user destructor be sure to flag the
405         // destructor as running for this thread so calls to `get` will return
406         // `None`.
407         (*ptr).dtor_running.set(true);
408
409         // Some implementations may require us to move the value before we drop
410         // it as it could get re-initialized in-place during destruction.
411         //
412         // Hence, we use `ptr::read` on those platforms (to move to a "safe"
413         // location) instead of drop_in_place.
414         if requires_move_before_drop() {
415             ptr::read((*ptr).inner.get());
416         } else {
417             ptr::drop_in_place((*ptr).inner.get());
418         }
419     }
420 }
421
422 #[doc(hidden)]
423 pub mod os {
424     use cell::{Cell, UnsafeCell};
425     use fmt;
426     use marker;
427     use ptr;
428     use sys_common::thread_local::StaticKey as OsStaticKey;
429
430     pub struct Key<T> {
431         // OS-TLS key that we'll use to key off.
432         os: OsStaticKey,
433         marker: marker::PhantomData<Cell<T>>,
434     }
435
436     impl<T> fmt::Debug for Key<T> {
437         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438             f.pad("Key { .. }")
439         }
440     }
441
442     unsafe impl<T> ::marker::Sync for Key<T> { }
443
444     struct Value<T: 'static> {
445         key: &'static Key<T>,
446         value: UnsafeCell<Option<T>>,
447     }
448
449     impl<T: 'static> Key<T> {
450         pub const fn new() -> Key<T> {
451             Key {
452                 os: OsStaticKey::new(Some(destroy_value::<T>)),
453                 marker: marker::PhantomData
454             }
455         }
456
457         pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
458             let ptr = self.os.get() as *mut Value<T>;
459             if !ptr.is_null() {
460                 if ptr as usize == 1 {
461                     return None
462                 }
463                 return Some(&(*ptr).value);
464             }
465
466             // If the lookup returned null, we haven't initialized our own
467             // local copy, so do that now.
468             let ptr: Box<Value<T>> = box Value {
469                 key: self,
470                 value: UnsafeCell::new(None),
471             };
472             let ptr = Box::into_raw(ptr);
473             self.os.set(ptr as *mut u8);
474             Some(&(*ptr).value)
475         }
476     }
477
478     unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
479         // The OS TLS ensures that this key contains a NULL value when this
480         // destructor starts to run. We set it back to a sentinel value of 1 to
481         // ensure that any future calls to `get` for this thread will return
482         // `None`.
483         //
484         // Note that to prevent an infinite loop we reset it back to null right
485         // before we return from the destructor ourselves.
486         let ptr = Box::from_raw(ptr as *mut Value<T>);
487         let key = ptr.key;
488         key.os.set(1 as *mut u8);
489         drop(ptr);
490         key.os.set(ptr::null_mut());
491     }
492 }
493
494 #[cfg(all(test, not(target_os = "emscripten")))]
495 mod tests {
496     use sync::mpsc::{channel, Sender};
497     use cell::{Cell, UnsafeCell};
498     use thread;
499
500     struct Foo(Sender<()>);
501
502     impl Drop for Foo {
503         fn drop(&mut self) {
504             let Foo(ref s) = *self;
505             s.send(()).unwrap();
506         }
507     }
508
509     #[test]
510     fn smoke_no_dtor() {
511         thread_local!(static FOO: Cell<i32> = Cell::new(1));
512
513         FOO.with(|f| {
514             assert_eq!(f.get(), 1);
515             f.set(2);
516         });
517         let (tx, rx) = channel();
518         let _t = thread::spawn(move|| {
519             FOO.with(|f| {
520                 assert_eq!(f.get(), 1);
521             });
522             tx.send(()).unwrap();
523         });
524         rx.recv().unwrap();
525
526         FOO.with(|f| {
527             assert_eq!(f.get(), 2);
528         });
529     }
530
531     #[test]
532     fn states() {
533         struct Foo;
534         impl Drop for Foo {
535             fn drop(&mut self) {
536                 assert!(FOO.try_with(|_| ()).is_err());
537             }
538         }
539         thread_local!(static FOO: Foo = Foo);
540
541         thread::spawn(|| {
542             assert!(FOO.try_with(|_| ()).is_ok());
543         }).join().ok().unwrap();
544     }
545
546     #[test]
547     fn smoke_dtor() {
548         thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
549
550         let (tx, rx) = channel();
551         let _t = thread::spawn(move|| unsafe {
552             let mut tx = Some(tx);
553             FOO.with(|f| {
554                 *f.get() = Some(Foo(tx.take().unwrap()));
555             });
556         });
557         rx.recv().unwrap();
558     }
559
560     #[test]
561     fn circular() {
562         struct S1;
563         struct S2;
564         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
565         thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
566         static mut HITS: u32 = 0;
567
568         impl Drop for S1 {
569             fn drop(&mut self) {
570                 unsafe {
571                     HITS += 1;
572                     if K2.try_with(|_| ()).is_err() {
573                         assert_eq!(HITS, 3);
574                     } else {
575                         if HITS == 1 {
576                             K2.with(|s| *s.get() = Some(S2));
577                         } else {
578                             assert_eq!(HITS, 3);
579                         }
580                     }
581                 }
582             }
583         }
584         impl Drop for S2 {
585             fn drop(&mut self) {
586                 unsafe {
587                     HITS += 1;
588                     assert!(K1.try_with(|_| ()).is_ok());
589                     assert_eq!(HITS, 2);
590                     K1.with(|s| *s.get() = Some(S1));
591                 }
592             }
593         }
594
595         thread::spawn(move|| {
596             drop(S1);
597         }).join().ok().unwrap();
598     }
599
600     #[test]
601     fn self_referential() {
602         struct S1;
603         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
604
605         impl Drop for S1 {
606             fn drop(&mut self) {
607                 assert!(K1.try_with(|_| ()).is_err());
608             }
609         }
610
611         thread::spawn(move|| unsafe {
612             K1.with(|s| *s.get() = Some(S1));
613         }).join().ok().unwrap();
614     }
615
616     // Note that this test will deadlock if TLS destructors aren't run (this
617     // requires the destructor to be run to pass the test). macOS has a known bug
618     // where dtors-in-dtors may cancel other destructors, so we just ignore this
619     // test on macOS.
620     #[test]
621     #[cfg_attr(target_os = "macos", ignore)]
622     fn dtors_in_dtors_in_dtors() {
623         struct S1(Sender<()>);
624         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
625         thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
626
627         impl Drop for S1 {
628             fn drop(&mut self) {
629                 let S1(ref tx) = *self;
630                 unsafe {
631                     let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone())));
632                 }
633             }
634         }
635
636         let (tx, rx) = channel();
637         let _t = thread::spawn(move|| unsafe {
638             let mut tx = Some(tx);
639             K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
640         });
641         rx.recv().unwrap();
642     }
643 }
644
645 #[cfg(test)]
646 mod dynamic_tests {
647     use cell::RefCell;
648     use collections::HashMap;
649
650     #[test]
651     fn smoke() {
652         fn square(i: i32) -> i32 { i * i }
653         thread_local!(static FOO: i32 = square(3));
654
655         FOO.with(|f| {
656             assert_eq!(*f, 9);
657         });
658     }
659
660     #[test]
661     fn hashmap() {
662         fn map() -> RefCell<HashMap<i32, i32>> {
663             let mut m = HashMap::new();
664             m.insert(1, 2);
665             RefCell::new(m)
666         }
667         thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
668
669         FOO.with(|map| {
670             assert_eq!(map.borrow()[&1], 2);
671         });
672     }
673
674     #[test]
675     fn refcell_vec() {
676         thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
677
678         FOO.with(|vec| {
679             assert_eq!(vec.borrow().len(), 3);
680             vec.borrow_mut().push(4);
681             assert_eq!(vec.borrow()[3], 4);
682         });
683     }
684 }