]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/thread_local.rs
Auto merge of #43710 - zackmdavis:field_init_shorthand_power_slam, r=Mark-Simulacrum
[rust.git] / src / libstd / sys_common / thread_local.rs
1 // Copyright 2014 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 //! OS-based thread local storage
12 //!
13 //! This module provides an implementation of OS-based thread local storage,
14 //! using the native OS-provided facilities (think `TlsAlloc` or
15 //! `pthread_setspecific`). The interface of this differs from the other types
16 //! of thread-local-storage provided in this crate in that OS-based TLS can only
17 //! get/set pointers,
18 //!
19 //! This module also provides two flavors of TLS. One is intended for static
20 //! initialization, and does not contain a `Drop` implementation to deallocate
21 //! the OS-TLS key. The other is a type which does implement `Drop` and hence
22 //! has a safe interface.
23 //!
24 //! # Usage
25 //!
26 //! This module should likely not be used directly unless other primitives are
27 //! being built on. types such as `thread_local::spawn::Key` are likely much
28 //! more useful in practice than this OS-based version which likely requires
29 //! unsafe code to interoperate with.
30 //!
31 //! # Examples
32 //!
33 //! Using a dynamically allocated TLS key. Note that this key can be shared
34 //! among many threads via an `Arc`.
35 //!
36 //! ```ignore (cannot-doctest-private-modules)
37 //! let key = Key::new(None);
38 //! assert!(key.get().is_null());
39 //! key.set(1 as *mut u8);
40 //! assert!(!key.get().is_null());
41 //!
42 //! drop(key); // deallocate this TLS slot.
43 //! ```
44 //!
45 //! Sometimes a statically allocated key is either required or easier to work
46 //! with, however.
47 //!
48 //! ```ignore (cannot-doctest-private-modules)
49 //! static KEY: StaticKey = INIT;
50 //!
51 //! unsafe {
52 //!     assert!(KEY.get().is_null());
53 //!     KEY.set(1 as *mut u8);
54 //! }
55 //! ```
56
57 #![allow(non_camel_case_types)]
58 #![unstable(feature = "thread_local_internals", issue = "0")]
59 #![allow(dead_code)] // sys isn't exported yet
60
61 use ptr;
62 use sync::atomic::{self, AtomicUsize, Ordering};
63 use sys::thread_local as imp;
64 use sys_common::mutex::Mutex;
65
66 /// A type for TLS keys that are statically allocated.
67 ///
68 /// This type is entirely `unsafe` to use as it does not protect against
69 /// use-after-deallocation or use-during-deallocation.
70 ///
71 /// The actual OS-TLS key is lazily allocated when this is used for the first
72 /// time. The key is also deallocated when the Rust runtime exits or `destroy`
73 /// is called, whichever comes first.
74 ///
75 /// # Examples
76 ///
77 /// ```ignore (cannot-doctest-private-modules)
78 /// use tls::os::{StaticKey, INIT};
79 ///
80 /// static KEY: StaticKey = INIT;
81 ///
82 /// unsafe {
83 ///     assert!(KEY.get().is_null());
84 ///     KEY.set(1 as *mut u8);
85 /// }
86 /// ```
87 pub struct StaticKey {
88     /// Inner static TLS key (internals).
89     key: AtomicUsize,
90     /// Destructor for the TLS value.
91     ///
92     /// See `Key::new` for information about when the destructor runs and how
93     /// it runs.
94     dtor: Option<unsafe extern fn(*mut u8)>,
95 }
96
97 /// A type for a safely managed OS-based TLS slot.
98 ///
99 /// This type allocates an OS TLS key when it is initialized and will deallocate
100 /// the key when it falls out of scope. When compared with `StaticKey`, this
101 /// type is entirely safe to use.
102 ///
103 /// Implementations will likely, however, contain unsafe code as this type only
104 /// operates on `*mut u8`, a raw pointer.
105 ///
106 /// # Examples
107 ///
108 /// ```ignore (cannot-doctest-private-modules)
109 /// use tls::os::Key;
110 ///
111 /// let key = Key::new(None);
112 /// assert!(key.get().is_null());
113 /// key.set(1 as *mut u8);
114 /// assert!(!key.get().is_null());
115 ///
116 /// drop(key); // deallocate this TLS slot.
117 /// ```
118 pub struct Key {
119     key: imp::Key,
120 }
121
122 /// Constant initialization value for static TLS keys.
123 ///
124 /// This value specifies no destructor by default.
125 pub const INIT: StaticKey = StaticKey::new(None);
126
127 impl StaticKey {
128     pub const fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> StaticKey {
129         StaticKey {
130             key: atomic::AtomicUsize::new(0),
131             dtor,
132         }
133     }
134
135     /// Gets the value associated with this TLS key
136     ///
137     /// This will lazily allocate a TLS key from the OS if one has not already
138     /// been allocated.
139     #[inline]
140     pub unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) }
141
142     /// Sets this TLS key to a new value.
143     ///
144     /// This will lazily allocate a TLS key from the OS if one has not already
145     /// been allocated.
146     #[inline]
147     pub unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) }
148
149     #[inline]
150     unsafe fn key(&self) -> imp::Key {
151         match self.key.load(Ordering::Relaxed) {
152             0 => self.lazy_init() as imp::Key,
153             n => n as imp::Key
154         }
155     }
156
157     unsafe fn lazy_init(&self) -> usize {
158         // Currently the Windows implementation of TLS is pretty hairy, and
159         // it greatly simplifies creation if we just synchronize everything.
160         //
161         // Additionally a 0-index of a tls key hasn't been seen on windows, so
162         // we just simplify the whole branch.
163         if imp::requires_synchronized_create() {
164             static INIT_LOCK: Mutex = Mutex::new();
165             INIT_LOCK.lock();
166             let mut key = self.key.load(Ordering::SeqCst);
167             if key == 0 {
168                 key = imp::create(self.dtor) as usize;
169                 self.key.store(key, Ordering::SeqCst);
170             }
171             INIT_LOCK.unlock();
172             assert!(key != 0);
173             return key
174         }
175
176         // POSIX allows the key created here to be 0, but the compare_and_swap
177         // below relies on using 0 as a sentinel value to check who won the
178         // race to set the shared TLS key. As far as I know, there is no
179         // guaranteed value that cannot be returned as a posix_key_create key,
180         // so there is no value we can initialize the inner key with to
181         // prove that it has not yet been set. As such, we'll continue using a
182         // value of 0, but with some gyrations to make sure we have a non-0
183         // value returned from the creation routine.
184         // FIXME: this is clearly a hack, and should be cleaned up.
185         let key1 = imp::create(self.dtor);
186         let key = if key1 != 0 {
187             key1
188         } else {
189             let key2 = imp::create(self.dtor);
190             imp::destroy(key1);
191             key2
192         };
193         assert!(key != 0);
194         match self.key.compare_and_swap(0, key as usize, Ordering::SeqCst) {
195             // The CAS succeeded, so we've created the actual key
196             0 => key as usize,
197             // If someone beat us to the punch, use their key instead
198             n => { imp::destroy(key); n }
199         }
200     }
201 }
202
203 impl Key {
204     /// Creates a new managed OS TLS key.
205     ///
206     /// This key will be deallocated when the key falls out of scope.
207     ///
208     /// The argument provided is an optionally-specified destructor for the
209     /// value of this TLS key. When a thread exits and the value for this key
210     /// is non-null the destructor will be invoked. The TLS value will be reset
211     /// to null before the destructor is invoked.
212     ///
213     /// Note that the destructor will not be run when the `Key` goes out of
214     /// scope.
215     #[inline]
216     pub fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
217         Key { key: unsafe { imp::create(dtor) } }
218     }
219
220     /// See StaticKey::get
221     #[inline]
222     pub fn get(&self) -> *mut u8 {
223         unsafe { imp::get(self.key) }
224     }
225
226     /// See StaticKey::set
227     #[inline]
228     pub fn set(&self, val: *mut u8) {
229         unsafe { imp::set(self.key, val) }
230     }
231 }
232
233 impl Drop for Key {
234     fn drop(&mut self) {
235         // Right now Windows doesn't support TLS key destruction, but this also
236         // isn't used anywhere other than tests, so just leak the TLS key.
237         // unsafe { imp::destroy(self.key) }
238     }
239 }
240
241 pub unsafe fn register_dtor_fallback(t: *mut u8,
242                                      dtor: unsafe extern fn(*mut u8)) {
243     // The fallback implementation uses a vanilla OS-based TLS key to track
244     // the list of destructors that need to be run for this thread. The key
245     // then has its own destructor which runs all the other destructors.
246     //
247     // The destructor for DTORS is a little special in that it has a `while`
248     // loop to continuously drain the list of registered destructors. It
249     // *should* be the case that this loop always terminates because we
250     // provide the guarantee that a TLS key cannot be set after it is
251     // flagged for destruction.
252
253     static DTORS: StaticKey = StaticKey::new(Some(run_dtors));
254     type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>;
255     if DTORS.get().is_null() {
256         let v: Box<List> = box Vec::new();
257         DTORS.set(Box::into_raw(v) as *mut u8);
258     }
259     let list: &mut List = &mut *(DTORS.get() as *mut List);
260     list.push((t, dtor));
261
262     unsafe extern fn run_dtors(mut ptr: *mut u8) {
263         while !ptr.is_null() {
264             let list: Box<List> = Box::from_raw(ptr as *mut List);
265             for &(ptr, dtor) in list.iter() {
266                 dtor(ptr);
267             }
268             ptr = DTORS.get();
269             DTORS.set(ptr::null_mut());
270         }
271     }
272 }
273
274 #[cfg(test)]
275 mod tests {
276     use super::{Key, StaticKey};
277
278     fn assert_sync<T: Sync>() {}
279     fn assert_send<T: Send>() {}
280
281     #[test]
282     fn smoke() {
283         assert_sync::<Key>();
284         assert_send::<Key>();
285
286         let k1 = Key::new(None);
287         let k2 = Key::new(None);
288         assert!(k1.get().is_null());
289         assert!(k2.get().is_null());
290         k1.set(1 as *mut _);
291         k2.set(2 as *mut _);
292         assert_eq!(k1.get() as usize, 1);
293         assert_eq!(k2.get() as usize, 2);
294     }
295
296     #[test]
297     fn statik() {
298         static K1: StaticKey = StaticKey::new(None);
299         static K2: StaticKey = StaticKey::new(None);
300
301         unsafe {
302             assert!(K1.get().is_null());
303             assert!(K2.get().is_null());
304             K1.set(1 as *mut _);
305             K2.set(2 as *mut _);
306             assert_eq!(K1.get() as usize, 1);
307             assert_eq!(K2.get() as usize, 2);
308         }
309     }
310 }