]> git.lizzy.rs Git - rust.git/blob - src/libstd/thread/local.rs
add inline attributes to stage 0 methods
[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 OSX, 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 #[stable(feature = "rust1", since = "1.0.0")]
81 pub struct LocalKey<T: 'static> {
82     // This outer `LocalKey<T>` type is what's going to be stored in statics,
83     // but actual data inside will sometimes be tagged with #[thread_local].
84     // It's not valid for a true static to reference a #[thread_local] static,
85     // so we get around that by exposing an accessor through a layer of function
86     // indirection (this thunk).
87     //
88     // Note that the thunk is itself unsafe because the returned lifetime of the
89     // slot where data lives, `'static`, is not actually valid. The lifetime
90     // here is actually `'thread`!
91     //
92     // Although this is an extra layer of indirection, it should in theory be
93     // trivially devirtualizable by LLVM because the value of `inner` never
94     // changes and the constant should be readonly within a crate. This mainly
95     // only runs into problems when TLS statics are exported across crates.
96     inner: fn() -> Option<&'static UnsafeCell<Option<T>>>,
97
98     // initialization routine to invoke to create a value
99     init: fn() -> T,
100 }
101
102 #[stable(feature = "std_debug", since = "1.16.0")]
103 impl<T: 'static> fmt::Debug for LocalKey<T> {
104     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105         f.pad("LocalKey { .. }")
106     }
107 }
108
109 /// Declare a new thread local storage key of type `std::thread::LocalKey`.
110 ///
111 /// # Syntax
112 ///
113 /// The macro wraps any number of static declarations and makes them thread local.
114 /// Each static may be public or private, and attributes are allowed. Example:
115 ///
116 /// ```
117 /// use std::cell::RefCell;
118 /// thread_local! {
119 ///     pub static FOO: RefCell<u32> = RefCell::new(1);
120 ///
121 ///     #[allow(unused)]
122 ///     static BAR: RefCell<f32> = RefCell::new(1.0);
123 /// }
124 /// # fn main() {}
125 /// ```
126 ///
127 /// See [LocalKey documentation](thread/struct.LocalKey.html) for more
128 /// information.
129 #[macro_export]
130 #[stable(feature = "rust1", since = "1.0.0")]
131 #[allow_internal_unstable]
132 macro_rules! thread_local {
133     // rule 0: empty (base case for the recursion)
134     () => {};
135
136     // rule 1: process multiple declarations where the first one is private
137     ($(#[$attr:meta])* static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
138         thread_local!($(#[$attr])* static $name: $t = $init); // go to rule 2
139         thread_local!($($rest)*);
140     );
141
142     // rule 2: handle a single private declaration
143     ($(#[$attr:meta])* static $name:ident: $t:ty = $init:expr) => (
144         $(#[$attr])* static $name: $crate::thread::LocalKey<$t> =
145             __thread_local_inner!($t, $init);
146     );
147
148     // rule 3: handle multiple declarations where the first one is public
149     ($(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
150         thread_local!($(#[$attr])* pub static $name: $t = $init); // go to rule 4
151         thread_local!($($rest)*);
152     );
153
154     // rule 4: handle a single public declaration
155     ($(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr) => (
156         $(#[$attr])* pub static $name: $crate::thread::LocalKey<$t> =
157             __thread_local_inner!($t, $init);
158     );
159 }
160
161 #[doc(hidden)]
162 #[unstable(feature = "thread_local_internals",
163            reason = "should not be necessary",
164            issue = "0")]
165 #[macro_export]
166 #[allow_internal_unstable]
167 macro_rules! __thread_local_inner {
168     ($t:ty, $init:expr) => {{
169         fn __init() -> $t { $init }
170
171         fn __getit() -> $crate::option::Option<
172             &'static $crate::cell::UnsafeCell<
173                 $crate::option::Option<$t>>>
174         {
175             #[thread_local]
176             #[cfg(target_thread_local)]
177             static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
178                 $crate::thread::__FastLocalKeyInner::new();
179
180             #[cfg(not(target_thread_local))]
181             static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
182                 $crate::thread::__OsLocalKeyInner::new();
183
184             __KEY.get()
185         }
186
187         $crate::thread::LocalKey::new(__getit, __init)
188     }}
189 }
190
191 /// Indicator of the state of a thread local storage key.
192 #[unstable(feature = "thread_local_state",
193            reason = "state querying was recently added",
194            issue = "27716")]
195 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
196 pub enum LocalKeyState {
197     /// All keys are in this state whenever a thread starts. Keys will
198     /// transition to the `Valid` state once the first call to `with` happens
199     /// and the initialization expression succeeds.
200     ///
201     /// Keys in the `Uninitialized` state will yield a reference to the closure
202     /// passed to `with` so long as the initialization routine does not panic.
203     Uninitialized,
204
205     /// Once a key has been accessed successfully, it will enter the `Valid`
206     /// state. Keys in the `Valid` state will remain so until the thread exits,
207     /// at which point the destructor will be run and the key will enter the
208     /// `Destroyed` state.
209     ///
210     /// Keys in the `Valid` state will be guaranteed to yield a reference to the
211     /// closure passed to `with`.
212     Valid,
213
214     /// When a thread exits, the destructors for keys will be run (if
215     /// necessary). While a destructor is running, and possibly after a
216     /// destructor has run, a key is in the `Destroyed` state.
217     ///
218     /// Keys in the `Destroyed` states will trigger a panic when accessed via
219     /// `with`.
220     Destroyed,
221 }
222
223 impl<T: 'static> LocalKey<T> {
224     #[doc(hidden)]
225     #[unstable(feature = "thread_local_internals",
226                reason = "recently added to create a key",
227                issue = "0")]
228     pub const fn new(inner: fn() -> Option<&'static UnsafeCell<Option<T>>>,
229                      init: fn() -> T) -> LocalKey<T> {
230         LocalKey {
231             inner: inner,
232             init: init,
233         }
234     }
235
236     /// Acquires a reference to the value in this TLS key.
237     ///
238     /// This will lazily initialize the value if this thread has not referenced
239     /// this key yet.
240     ///
241     /// # Panics
242     ///
243     /// This function will `panic!()` if the key currently has its
244     /// destructor running, and it **may** panic if the destructor has
245     /// previously been run for this thread.
246     #[stable(feature = "rust1", since = "1.0.0")]
247     pub fn with<F, R>(&'static self, f: F) -> R
248                       where F: FnOnce(&T) -> R {
249         unsafe {
250             let slot = (self.inner)();
251             let slot = slot.expect("cannot access a TLS value during or \
252                                     after it is destroyed");
253             f(match *slot.get() {
254                 Some(ref inner) => inner,
255                 None => self.init(slot),
256             })
257         }
258     }
259
260     unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T {
261         // Execute the initialization up front, *then* move it into our slot,
262         // just in case initialization fails.
263         let value = (self.init)();
264         let ptr = slot.get();
265
266         // note that this can in theory just be `*ptr = Some(value)`, but due to
267         // the compiler will currently codegen that pattern with something like:
268         //
269         //      ptr::drop_in_place(ptr)
270         //      ptr::write(ptr, Some(value))
271         //
272         // Due to this pattern it's possible for the destructor of the value in
273         // `ptr` (e.g. if this is being recursively initialized) to re-access
274         // TLS, in which case there will be a `&` and `&mut` pointer to the same
275         // value (an aliasing violation). To avoid setting the "I'm running a
276         // destructor" flag we just use `mem::replace` which should sequence the
277         // operations a little differently and make this safe to call.
278         mem::replace(&mut *ptr, Some(value));
279
280         (*ptr).as_ref().unwrap()
281     }
282
283     /// Query the current state of this key.
284     ///
285     /// A key is initially in the `Uninitialized` state whenever a thread
286     /// starts. It will remain in this state up until the first call to `with`
287     /// within a thread has run the initialization expression successfully.
288     ///
289     /// Once the initialization expression succeeds, the key transitions to the
290     /// `Valid` state which will guarantee that future calls to `with` will
291     /// succeed within the thread.
292     ///
293     /// When a thread exits, each key will be destroyed in turn, and as keys are
294     /// destroyed they will enter the `Destroyed` state just before the
295     /// destructor starts to run. Keys may remain in the `Destroyed` state after
296     /// destruction has completed. Keys without destructors (e.g. with types
297     /// that are `Copy`), may never enter the `Destroyed` state.
298     ///
299     /// Keys in the `Uninitialized` state can be accessed so long as the
300     /// initialization does not panic. Keys in the `Valid` state are guaranteed
301     /// to be able to be accessed. Keys in the `Destroyed` state will panic on
302     /// any call to `with`.
303     #[unstable(feature = "thread_local_state",
304                reason = "state querying was recently added",
305                issue = "27716")]
306     pub fn state(&'static self) -> LocalKeyState {
307         unsafe {
308             match (self.inner)() {
309                 Some(cell) => {
310                     match *cell.get() {
311                         Some(..) => LocalKeyState::Valid,
312                         None => LocalKeyState::Uninitialized,
313                     }
314                 }
315                 None => LocalKeyState::Destroyed,
316             }
317         }
318     }
319 }
320
321 #[doc(hidden)]
322 pub mod os {
323     use cell::{Cell, UnsafeCell};
324     use fmt;
325     use marker;
326     use ptr;
327     use sys_common::thread_local::StaticKey as OsStaticKey;
328
329     pub struct Key<T> {
330         // OS-TLS key that we'll use to key off.
331         os: OsStaticKey,
332         marker: marker::PhantomData<Cell<T>>,
333     }
334
335     impl<T> fmt::Debug for Key<T> {
336         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337             f.pad("Key { .. }")
338         }
339     }
340
341     unsafe impl<T> ::marker::Sync for Key<T> { }
342
343     struct Value<T: 'static> {
344         key: &'static Key<T>,
345         value: UnsafeCell<Option<T>>,
346     }
347
348     impl<T: 'static> Key<T> {
349         pub const fn new() -> Key<T> {
350             Key {
351                 os: OsStaticKey::new(Some(destroy_value::<T>)),
352                 marker: marker::PhantomData
353             }
354         }
355
356         pub fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> {
357             unsafe {
358                 let ptr = self.os.get() as *mut Value<T>;
359                 if !ptr.is_null() {
360                     if ptr as usize == 1 {
361                         return None
362                     }
363                     return Some(&(*ptr).value);
364                 }
365
366                 // If the lookup returned null, we haven't initialized our own local
367                 // copy, so do that now.
368                 let ptr: Box<Value<T>> = box Value {
369                     key: self,
370                     value: UnsafeCell::new(None),
371                 };
372                 let ptr = Box::into_raw(ptr);
373                 self.os.set(ptr as *mut u8);
374                 Some(&(*ptr).value)
375             }
376         }
377     }
378
379     pub unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) {
380         // The OS TLS ensures that this key contains a NULL value when this
381         // destructor starts to run. We set it back to a sentinel value of 1 to
382         // ensure that any future calls to `get` for this thread will return
383         // `None`.
384         //
385         // Note that to prevent an infinite loop we reset it back to null right
386         // before we return from the destructor ourselves.
387         let ptr = Box::from_raw(ptr as *mut Value<T>);
388         let key = ptr.key;
389         key.os.set(1 as *mut u8);
390         drop(ptr);
391         key.os.set(ptr::null_mut());
392     }
393 }
394
395 #[cfg(all(test, not(target_os = "emscripten")))]
396 mod tests {
397     use sync::mpsc::{channel, Sender};
398     use cell::{Cell, UnsafeCell};
399     use super::LocalKeyState;
400     use thread;
401
402     struct Foo(Sender<()>);
403
404     impl Drop for Foo {
405         fn drop(&mut self) {
406             let Foo(ref s) = *self;
407             s.send(()).unwrap();
408         }
409     }
410
411     #[test]
412     fn smoke_no_dtor() {
413         thread_local!(static FOO: Cell<i32> = Cell::new(1));
414
415         FOO.with(|f| {
416             assert_eq!(f.get(), 1);
417             f.set(2);
418         });
419         let (tx, rx) = channel();
420         let _t = thread::spawn(move|| {
421             FOO.with(|f| {
422                 assert_eq!(f.get(), 1);
423             });
424             tx.send(()).unwrap();
425         });
426         rx.recv().unwrap();
427
428         FOO.with(|f| {
429             assert_eq!(f.get(), 2);
430         });
431     }
432
433     #[test]
434     fn states() {
435         struct Foo;
436         impl Drop for Foo {
437             fn drop(&mut self) {
438                 assert!(FOO.state() == LocalKeyState::Destroyed);
439             }
440         }
441         fn foo() -> Foo {
442             assert!(FOO.state() == LocalKeyState::Uninitialized);
443             Foo
444         }
445         thread_local!(static FOO: Foo = foo());
446
447         thread::spawn(|| {
448             assert!(FOO.state() == LocalKeyState::Uninitialized);
449             FOO.with(|_| {
450                 assert!(FOO.state() == LocalKeyState::Valid);
451             });
452             assert!(FOO.state() == LocalKeyState::Valid);
453         }).join().ok().unwrap();
454     }
455
456     #[test]
457     fn smoke_dtor() {
458         thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
459
460         let (tx, rx) = channel();
461         let _t = thread::spawn(move|| unsafe {
462             let mut tx = Some(tx);
463             FOO.with(|f| {
464                 *f.get() = Some(Foo(tx.take().unwrap()));
465             });
466         });
467         rx.recv().unwrap();
468     }
469
470     #[test]
471     fn circular() {
472         struct S1;
473         struct S2;
474         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
475         thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None));
476         static mut HITS: u32 = 0;
477
478         impl Drop for S1 {
479             fn drop(&mut self) {
480                 unsafe {
481                     HITS += 1;
482                     if K2.state() == LocalKeyState::Destroyed {
483                         assert_eq!(HITS, 3);
484                     } else {
485                         if HITS == 1 {
486                             K2.with(|s| *s.get() = Some(S2));
487                         } else {
488                             assert_eq!(HITS, 3);
489                         }
490                     }
491                 }
492             }
493         }
494         impl Drop for S2 {
495             fn drop(&mut self) {
496                 unsafe {
497                     HITS += 1;
498                     assert!(K1.state() != LocalKeyState::Destroyed);
499                     assert_eq!(HITS, 2);
500                     K1.with(|s| *s.get() = Some(S1));
501                 }
502             }
503         }
504
505         thread::spawn(move|| {
506             drop(S1);
507         }).join().ok().unwrap();
508     }
509
510     #[test]
511     fn self_referential() {
512         struct S1;
513         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
514
515         impl Drop for S1 {
516             fn drop(&mut self) {
517                 assert!(K1.state() == LocalKeyState::Destroyed);
518             }
519         }
520
521         thread::spawn(move|| unsafe {
522             K1.with(|s| *s.get() = Some(S1));
523         }).join().ok().unwrap();
524     }
525
526     // Note that this test will deadlock if TLS destructors aren't run (this
527     // requires the destructor to be run to pass the test). OSX has a known bug
528     // where dtors-in-dtors may cancel other destructors, so we just ignore this
529     // test on OSX.
530     #[test]
531     #[cfg_attr(target_os = "macos", ignore)]
532     fn dtors_in_dtors_in_dtors() {
533         struct S1(Sender<()>);
534         thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None));
535         thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None));
536
537         impl Drop for S1 {
538             fn drop(&mut self) {
539                 let S1(ref tx) = *self;
540                 unsafe {
541                     if K2.state() != LocalKeyState::Destroyed {
542                         K2.with(|s| *s.get() = Some(Foo(tx.clone())));
543                     }
544                 }
545             }
546         }
547
548         let (tx, rx) = channel();
549         let _t = thread::spawn(move|| unsafe {
550             let mut tx = Some(tx);
551             K1.with(|s| *s.get() = Some(S1(tx.take().unwrap())));
552         });
553         rx.recv().unwrap();
554     }
555 }
556
557 #[cfg(test)]
558 mod dynamic_tests {
559     use cell::RefCell;
560     use collections::HashMap;
561
562     #[test]
563     fn smoke() {
564         fn square(i: i32) -> i32 { i * i }
565         thread_local!(static FOO: i32 = square(3));
566
567         FOO.with(|f| {
568             assert_eq!(*f, 9);
569         });
570     }
571
572     #[test]
573     fn hashmap() {
574         fn map() -> RefCell<HashMap<i32, i32>> {
575             let mut m = HashMap::new();
576             m.insert(1, 2);
577             RefCell::new(m)
578         }
579         thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
580
581         FOO.with(|map| {
582             assert_eq!(map.borrow()[&1], 2);
583         });
584     }
585
586     #[test]
587     fn refcell_vec() {
588         thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3]));
589
590         FOO.with(|vec| {
591             assert_eq!(vec.borrow().len(), 3);
592             vec.borrow_mut().push(4);
593             assert_eq!(vec.borrow()[3], 4);
594         });
595     }
596 }