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