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