]>
git.proxmox.com Git - rustc.git/blob - 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.
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.
11 //! Thread local storage
13 #![unstable(feature = "thread_local_internals", issue = "0")]
18 /// A thread local storage key which owns its contents.
20 /// This key uses the fastest possible implementation available to it for the
21 /// target platform. It is instantiated with the `thread_local!` macro and the
22 /// primary method is the `with` method.
24 /// The `with` method yields a reference to the contained value which cannot be
25 /// sent across threads or escape the given closure.
27 /// # Initialization and Destruction
29 /// Initialization is dynamically performed on the first call to `with()`
30 /// within a thread, and values support destructors which will be run when a
36 /// use std::cell::RefCell;
39 /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
42 /// assert_eq!(*f.borrow(), 1);
43 /// *f.borrow_mut() = 2;
46 /// // each thread starts out with the initial value of 1
47 /// thread::spawn(move|| {
49 /// assert_eq!(*f.borrow(), 1);
50 /// *f.borrow_mut() = 3;
54 /// // we retain our original value of 2 despite the child thread
56 /// assert_eq!(*f.borrow(), 2);
60 /// # Platform-specific behavior
62 /// Note that a "best effort" is made to ensure that destructors for types
63 /// stored in thread local storage are run, but not all platforms can guarantee
64 /// that destructors will be run for all types in thread local storage. For
65 /// example, there are a number of known caveats where destructors are not run:
67 /// 1. On Unix systems when pthread-based TLS is being used, destructors will
68 /// not be run for TLS values on the main thread when it exits. Note that the
69 /// application will exit immediately after the main thread exits as well.
70 /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots
71 /// during destruction. Some platforms ensure that this cannot happen
72 /// infinitely by preventing re-initialization of any slot that has been
73 /// destroyed, but not all platforms have this guard. Those platforms that do
74 /// not guard typically have a synthetic limit after which point no more
75 /// destructors are run.
76 /// 3. On OSX, initializing TLS during destruction of other TLS slots can
77 /// sometimes cancel *all* destructors for the current thread, whether or not
78 /// the slots have already had their destructors run or not.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct LocalKey
<T
: '
static> {
81 // This outer `LocalKey<T>` type is what's going to be stored in statics,
82 // but actual data inside will sometimes be tagged with #[thread_local].
83 // It's not valid for a true static to reference a #[thread_local] static,
84 // so we get around that by exposing an accessor through a layer of function
85 // indirection (this thunk).
87 // Note that the thunk is itself unsafe because the returned lifetime of the
88 // slot where data lives, `'static`, is not actually valid. The lifetime
89 // here is actually `'thread`!
91 // Although this is an extra layer of indirection, it should in theory be
92 // trivially devirtualizable by LLVM because the value of `inner` never
93 // changes and the constant should be readonly within a crate. This mainly
94 // only runs into problems when TLS statics are exported across crates.
95 inner
: fn() -> Option
<&'
static UnsafeCell
<Option
<T
>>>,
97 // initialization routine to invoke to create a value
101 /// Declare a new thread local storage key of type `std::thread::LocalKey`.
105 /// The macro wraps any number of static declarations and makes them thread local.
106 /// Each static may be public or private, and attributes are allowed. Example:
109 /// use std::cell::RefCell;
111 /// pub static FOO: RefCell<u32> = RefCell::new(1);
114 /// static BAR: RefCell<f32> = RefCell::new(1.0);
119 /// See [LocalKey documentation](thread/struct.LocalKey.html) for more
122 #[stable(feature = "rust1", since = "1.0.0")]
123 #[allow_internal_unstable]
124 macro_rules
! thread_local
{
125 // rule 0: empty (base case for the recursion)
128 // rule 1: process multiple declarations where the first one is private
129 ($
(#[$attr:meta])* static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
130 thread_local
!($
(#[$attr])* static $name: $t = $init); // go to rule 2
131 thread_local
!($
($rest
)*);
134 // rule 2: handle a single private declaration
135 ($
(#[$attr:meta])* static $name:ident: $t:ty = $init:expr) => (
136 $
(#[$attr])* static $name: $crate::thread::LocalKey<$t> =
137 __thread_local_inner
!($t
, $init
);
140 // rule 3: handle multiple declarations where the first one is public
141 ($
(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
142 thread_local
!($
(#[$attr])* pub static $name: $t = $init); // go to rule 4
143 thread_local
!($
($rest
)*);
146 // rule 4: handle a single public declaration
147 ($
(#[$attr:meta])* pub static $name:ident: $t:ty = $init:expr) => (
148 $
(#[$attr])* pub static $name: $crate::thread::LocalKey<$t> =
149 __thread_local_inner
!($t
, $init
);
154 #[unstable(feature = "thread_local_internals",
155 reason
= "should not be necessary",
158 #[allow_internal_unstable]
159 macro_rules
! __thread_local_inner
{
160 ($t
:ty
, $init
:expr
) => {{
161 fn __init() -> $t { $init }
163 fn __getit() -> $
crate::option
::Option
<
164 &'
static $
crate::cell
::UnsafeCell
<
165 $
crate::option
::Option
<$t
>>>
168 #[cfg(target_thread_local)]
169 static __KEY
: $
crate::thread
::__ElfLocalKeyInner
<$t
> =
170 $
crate::thread
::__ElfLocalKeyInner
::new();
172 #[cfg(not(target_thread_local))]
173 static __KEY
: $
crate::thread
::__OsLocalKeyInner
<$t
> =
174 $
crate::thread
::__OsLocalKeyInner
::new();
179 $
crate::thread
::LocalKey
::new(__getit
, __init
)
183 /// Indicator of the state of a thread local storage key.
184 #[unstable(feature = "thread_local_state",
185 reason
= "state querying was recently added",
187 #[derive(Eq, PartialEq, Copy, Clone)]
188 pub enum LocalKeyState
{
189 /// All keys are in this state whenever a thread starts. Keys will
190 /// transition to the `Valid` state once the first call to `with` happens
191 /// and the initialization expression succeeds.
193 /// Keys in the `Uninitialized` state will yield a reference to the closure
194 /// passed to `with` so long as the initialization routine does not panic.
197 /// Once a key has been accessed successfully, it will enter the `Valid`
198 /// state. Keys in the `Valid` state will remain so until the thread exits,
199 /// at which point the destructor will be run and the key will enter the
200 /// `Destroyed` state.
202 /// Keys in the `Valid` state will be guaranteed to yield a reference to the
203 /// closure passed to `with`.
206 /// When a thread exits, the destructors for keys will be run (if
207 /// necessary). While a destructor is running, and possibly after a
208 /// destructor has run, a key is in the `Destroyed` state.
210 /// Keys in the `Destroyed` states will trigger a panic when accessed via
215 impl<T
: '
static> LocalKey
<T
> {
217 #[unstable(feature = "thread_local_internals",
218 reason
= "recently added to create a key",
220 pub const fn new(inner
: fn() -> Option
<&'
static UnsafeCell
<Option
<T
>>>,
221 init
: fn() -> T
) -> LocalKey
<T
> {
228 /// Acquires a reference to the value in this TLS key.
230 /// This will lazily initialize the value if this thread has not referenced
235 /// This function will `panic!()` if the key currently has its
236 /// destructor running, and it **may** panic if the destructor has
237 /// previously been run for this thread.
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn with
<F
, R
>(&'
static self, f
: F
) -> R
240 where F
: FnOnce(&T
) -> R
{
242 let slot
= (self.inner
)();
243 let slot
= slot
.expect("cannot access a TLS value during or \
244 after it is destroyed");
245 f(match *slot
.get() {
246 Some(ref inner
) => inner
,
247 None
=> self.init(slot
),
252 unsafe fn init(&self, slot
: &UnsafeCell
<Option
<T
>>) -> &T
{
253 // Execute the initialization up front, *then* move it into our slot,
254 // just in case initialization fails.
255 let value
= (self.init
)();
256 let ptr
= slot
.get();
258 // note that this can in theory just be `*ptr = Some(value)`, but due to
259 // the compiler will currently codegen that pattern with something like:
261 // ptr::drop_in_place(ptr)
262 // ptr::write(ptr, Some(value))
264 // Due to this pattern it's possible for the destructor of the value in
265 // `ptr` (e.g. if this is being recursively initialized) to re-access
266 // TLS, in which case there will be a `&` and `&mut` pointer to the same
267 // value (an aliasing violation). To avoid setting the "I'm running a
268 // destructor" flag we just use `mem::replace` which should sequence the
269 // operations a little differently and make this safe to call.
270 mem
::replace(&mut *ptr
, Some(value
));
272 (*ptr
).as_ref().unwrap()
275 /// Query the current state of this key.
277 /// A key is initially in the `Uninitialized` state whenever a thread
278 /// starts. It will remain in this state up until the first call to `with`
279 /// within a thread has run the initialization expression successfully.
281 /// Once the initialization expression succeeds, the key transitions to the
282 /// `Valid` state which will guarantee that future calls to `with` will
283 /// succeed within the thread.
285 /// When a thread exits, each key will be destroyed in turn, and as keys are
286 /// destroyed they will enter the `Destroyed` state just before the
287 /// destructor starts to run. Keys may remain in the `Destroyed` state after
288 /// destruction has completed. Keys without destructors (e.g. with types
289 /// that are `Copy`), may never enter the `Destroyed` state.
291 /// Keys in the `Uninitialized` state can be accessed so long as the
292 /// initialization does not panic. Keys in the `Valid` state are guaranteed
293 /// to be able to be accessed. Keys in the `Destroyed` state will panic on
294 /// any call to `with`.
295 #[unstable(feature = "thread_local_state",
296 reason
= "state querying was recently added",
298 pub fn state(&'
static self) -> LocalKeyState
{
300 match (self.inner
)() {
303 Some(..) => LocalKeyState
::Valid
,
304 None
=> LocalKeyState
::Uninitialized
,
307 None
=> LocalKeyState
::Destroyed
,
313 #[cfg(target_thread_local)]
316 use cell
::{Cell, UnsafeCell}
;
321 inner
: UnsafeCell
<Option
<T
>>,
323 // Metadata to keep track of the state of the destructor. Remember that
324 // these variables are thread-local, not global.
325 dtor_registered
: Cell
<bool
>,
326 dtor_running
: Cell
<bool
>,
329 unsafe impl<T
> ::marker
::Sync
for Key
<T
> { }
332 pub const fn new() -> Key
<T
> {
334 inner
: UnsafeCell
::new(None
),
335 dtor_registered
: Cell
::new(false),
336 dtor_running
: Cell
::new(false)
340 pub fn get(&'
static self) -> Option
<&'
static UnsafeCell
<Option
<T
>>> {
342 if intrinsics
::needs_drop
::<T
>() && self.dtor_running
.get() {
345 self.register_dtor();
350 unsafe fn register_dtor(&self) {
351 if !intrinsics
::needs_drop
::<T
>() || self.dtor_registered
.get() {
355 register_dtor(self as *const _
as *mut u8,
357 self.dtor_registered
.set(true);
361 // Since what appears to be glibc 2.18 this symbol has been shipped which
362 // GCC and clang both use to invoke destructors in thread_local globals, so
363 // let's do the same!
365 // Note, however, that we run on lots older linuxes, as well as cross
366 // compiling from a newer linux to an older linux, so we also have a
367 // fallback implementation to use as well.
369 // Due to rust-lang/rust#18804, make sure this is not generic!
370 #[cfg(target_os = "linux")]
371 unsafe fn register_dtor(t
: *mut u8, dtor
: unsafe extern fn(*mut u8)) {
374 use sys_common
::thread_local
as os
;
377 #[linkage = "extern_weak"]
378 static __dso_handle
: *mut u8;
379 #[linkage = "extern_weak"]
380 static __cxa_thread_atexit_impl
: *const libc
::c_void
;
382 if !__cxa_thread_atexit_impl
.is_null() {
383 type F
= unsafe extern fn(dtor
: unsafe extern fn(*mut u8),
385 dso_handle
: *mut u8) -> libc
::c_int
;
386 mem
::transmute
::<*const libc
::c_void
, F
>(__cxa_thread_atexit_impl
)
387 (dtor
, t
, &__dso_handle
as *const _
as *mut _
);
391 // The fallback implementation uses a vanilla OS-based TLS key to track
392 // the list of destructors that need to be run for this thread. The key
393 // then has its own destructor which runs all the other destructors.
395 // The destructor for DTORS is a little special in that it has a `while`
396 // loop to continuously drain the list of registered destructors. It
397 // *should* be the case that this loop always terminates because we
398 // provide the guarantee that a TLS key cannot be set after it is
399 // flagged for destruction.
400 static DTORS
: os
::StaticKey
= os
::StaticKey
::new(Some(run_dtors
));
401 type List
= Vec
<(*mut u8, unsafe extern fn(*mut u8))>;
402 if DTORS
.get().is_null() {
403 let v
: Box
<List
> = box Vec
::new();
404 DTORS
.set(Box
::into_raw(v
) as *mut u8);
406 let list
: &mut List
= &mut *(DTORS
.get() as *mut List
);
407 list
.push((t
, dtor
));
409 unsafe extern fn run_dtors(mut ptr
: *mut u8) {
410 while !ptr
.is_null() {
411 let list
: Box
<List
> = Box
::from_raw(ptr
as *mut List
);
412 for &(ptr
, dtor
) in list
.iter() {
416 DTORS
.set(ptr
::null_mut());
421 // OSX's analog of the above linux function is this _tlv_atexit function.
422 // The disassembly of thread_local globals in C++ (at least produced by
423 // clang) will have this show up in the output.
424 #[cfg(target_os = "macos")]
425 unsafe fn register_dtor(t
: *mut u8, dtor
: unsafe extern fn(*mut u8)) {
427 fn _tlv_atexit(dtor
: unsafe extern fn(*mut u8),
430 _tlv_atexit(dtor
, t
);
433 pub unsafe extern fn destroy_value
<T
>(ptr
: *mut u8) {
434 let ptr
= ptr
as *mut Key
<T
>;
435 // Right before we run the user destructor be sure to flag the
436 // destructor as running for this thread so calls to `get` will return
438 (*ptr
).dtor_running
.set(true);
440 // The OSX implementation of TLS apparently had an odd aspect to it
441 // where the pointer we have may be overwritten while this destructor
442 // is running. Specifically if a TLS destructor re-accesses TLS it may
443 // trigger a re-initialization of all TLS variables, paving over at
444 // least some destroyed ones with initial values.
446 // This means that if we drop a TLS value in place on OSX that we could
447 // revert the value to its original state halfway through the
448 // destructor, which would be bad!
450 // Hence, we use `ptr::read` on OSX (to move to a "safe" location)
451 // instead of drop_in_place.
452 if cfg
!(target_os
= "macos") {
453 ptr
::read((*ptr
).inner
.get());
455 ptr
::drop_in_place((*ptr
).inner
.get());
462 use cell
::{Cell, UnsafeCell}
;
465 use sys_common
::thread_local
::StaticKey
as OsStaticKey
;
468 // OS-TLS key that we'll use to key off.
470 marker
: marker
::PhantomData
<Cell
<T
>>,
473 unsafe impl<T
> ::marker
::Sync
for Key
<T
> { }
475 struct Value
<T
: '
static> {
476 key
: &'
static Key
<T
>,
477 value
: UnsafeCell
<Option
<T
>>,
480 impl<T
: '
static> Key
<T
> {
481 pub const fn new() -> Key
<T
> {
483 os
: OsStaticKey
::new(Some(destroy_value
::<T
>)),
484 marker
: marker
::PhantomData
488 pub fn get(&'
static self) -> Option
<&'
static UnsafeCell
<Option
<T
>>> {
490 let ptr
= self.os
.get() as *mut Value
<T
>;
492 if ptr
as usize == 1 {
495 return Some(&(*ptr
).value
);
498 // If the lookup returned null, we haven't initialized our own local
499 // copy, so do that now.
500 let ptr
: Box
<Value
<T
>> = box Value
{
502 value
: UnsafeCell
::new(None
),
504 let ptr
= Box
::into_raw(ptr
);
505 self.os
.set(ptr
as *mut u8);
511 pub unsafe extern fn destroy_value
<T
: '
static>(ptr
: *mut u8) {
512 // The OS TLS ensures that this key contains a NULL value when this
513 // destructor starts to run. We set it back to a sentinel value of 1 to
514 // ensure that any future calls to `get` for this thread will return
517 // Note that to prevent an infinite loop we reset it back to null right
518 // before we return from the destructor ourselves.
519 let ptr
= Box
::from_raw(ptr
as *mut Value
<T
>);
521 key
.os
.set(1 as *mut u8);
523 key
.os
.set(ptr
::null_mut());
529 use sync
::mpsc
::{channel, Sender}
;
530 use cell
::{Cell, UnsafeCell}
;
531 use super::LocalKeyState
;
534 struct Foo(Sender
<()>);
538 let Foo(ref s
) = *self;
545 thread_local
!(static FOO
: Cell
<i32> = Cell
::new(1));
548 assert_eq
!(f
.get(), 1);
551 let (tx
, rx
) = channel();
552 let _t
= thread
::spawn(move|| {
554 assert_eq
!(f
.get(), 1);
556 tx
.send(()).unwrap();
561 assert_eq
!(f
.get(), 2);
570 assert
!(FOO
.state() == LocalKeyState
::Destroyed
);
574 assert
!(FOO
.state() == LocalKeyState
::Uninitialized
);
577 thread_local
!(static FOO
: Foo
= foo());
580 assert
!(FOO
.state() == LocalKeyState
::Uninitialized
);
582 assert
!(FOO
.state() == LocalKeyState
::Valid
);
584 assert
!(FOO
.state() == LocalKeyState
::Valid
);
585 }).join().ok().unwrap();
590 thread_local
!(static FOO
: UnsafeCell
<Option
<Foo
>> = UnsafeCell
::new(None
));
592 let (tx
, rx
) = channel();
593 let _t
= thread
::spawn(move|| unsafe {
594 let mut tx
= Some(tx
);
596 *f
.get() = Some(Foo(tx
.take().unwrap()));
606 thread_local
!(static K1
: UnsafeCell
<Option
<S1
>> = UnsafeCell
::new(None
));
607 thread_local
!(static K2
: UnsafeCell
<Option
<S2
>> = UnsafeCell
::new(None
));
608 static mut HITS
: u32 = 0;
614 if K2
.state() == LocalKeyState
::Destroyed
{
618 K2
.with(|s
| *s
.get() = Some(S2
));
630 assert
!(K1
.state() != LocalKeyState
::Destroyed
);
632 K1
.with(|s
| *s
.get() = Some(S1
));
637 thread
::spawn(move|| {
639 }).join().ok().unwrap();
643 fn self_referential() {
645 thread_local
!(static K1
: UnsafeCell
<Option
<S1
>> = UnsafeCell
::new(None
));
649 assert
!(K1
.state() == LocalKeyState
::Destroyed
);
653 thread
::spawn(move|| unsafe {
654 K1
.with(|s
| *s
.get() = Some(S1
));
655 }).join().ok().unwrap();
658 // Note that this test will deadlock if TLS destructors aren't run (this
659 // requires the destructor to be run to pass the test). OSX has a known bug
660 // where dtors-in-dtors may cancel other destructors, so we just ignore this
663 #[cfg_attr(target_os = "macos", ignore)]
664 fn dtors_in_dtors_in_dtors() {
665 struct S1(Sender
<()>);
666 thread_local
!(static K1
: UnsafeCell
<Option
<S1
>> = UnsafeCell
::new(None
));
667 thread_local
!(static K2
: UnsafeCell
<Option
<Foo
>> = UnsafeCell
::new(None
));
671 let S1(ref tx
) = *self;
673 if K2
.state() != LocalKeyState
::Destroyed
{
674 K2
.with(|s
| *s
.get() = Some(Foo(tx
.clone())));
680 let (tx
, rx
) = channel();
681 let _t
= thread
::spawn(move|| unsafe {
682 let mut tx
= Some(tx
);
683 K1
.with(|s
| *s
.get() = Some(S1(tx
.take().unwrap())));
692 use collections
::HashMap
;
696 fn square(i
: i32) -> i32 { i * i }
697 thread_local
!(static FOO
: i32 = square(3));
706 fn map() -> RefCell
<HashMap
<i32, i32>> {
707 let mut m
= HashMap
::new();
711 thread_local
!(static FOO
: RefCell
<HashMap
<i32, i32>> = map());
714 assert_eq
!(map
.borrow()[&1], 2);
720 thread_local
!(static FOO
: RefCell
<Vec
<u32>> = RefCell
::new(vec
![1, 2, 3]));
723 assert_eq
!(vec
.borrow().len(), 3);
724 vec
.borrow_mut().push(4);
725 assert_eq
!(vec
.borrow()[3], 4);