]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/common/thread_local.rs
Merge pull request #20510 from tshepang/patch-6
[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::scoped::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 //! # Example
32 //!
33 //! Using a dynamically allocated TLS key. Note that this key can be shared
34 //! among many threads via an `Arc`.
35 //!
36 //! ```rust,ignore
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 //! ```rust,ignore
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
59 use prelude::v1::*;
60
61 use sync::atomic::{self, AtomicUint, Ordering};
62 use sync::{Mutex, Once, ONCE_INIT};
63
64 use sys::thread_local as imp;
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 /// # Example
76 ///
77 /// ```ignore
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), created with by `INIT_INNER` in this
89     /// module.
90     pub inner: StaticKeyInner,
91     /// Destructor for the TLS value.
92     ///
93     /// See `Key::new` for information about when the destructor runs and how
94     /// it runs.
95     pub dtor: Option<unsafe extern fn(*mut u8)>,
96 }
97
98 /// Inner contents of `StaticKey`, created by the `INIT_INNER` constant.
99 pub struct StaticKeyInner {
100     key: AtomicUint,
101 }
102
103 /// A type for a safely managed OS-based TLS slot.
104 ///
105 /// This type allocates an OS TLS key when it is initialized and will deallocate
106 /// the key when it falls out of scope. When compared with `StaticKey`, this
107 /// type is entirely safe to use.
108 ///
109 /// Implementations will likely, however, contain unsafe code as this type only
110 /// operates on `*mut u8`, an unsafe pointer.
111 ///
112 /// # Example
113 ///
114 /// ```rust,ignore
115 /// use tls::os::Key;
116 ///
117 /// let key = Key::new(None);
118 /// assert!(key.get().is_null());
119 /// key.set(1 as *mut u8);
120 /// assert!(!key.get().is_null());
121 ///
122 /// drop(key); // deallocate this TLS slot.
123 /// ```
124 pub struct Key {
125     key: imp::Key,
126 }
127
128 /// Constant initialization value for static TLS keys.
129 ///
130 /// This value specifies no destructor by default.
131 pub const INIT: StaticKey = StaticKey {
132     inner: INIT_INNER,
133     dtor: None,
134 };
135
136 /// Constant initialization value for the inner part of static TLS keys.
137 ///
138 /// This value allows specific configuration of the destructor for a TLS key.
139 pub const INIT_INNER: StaticKeyInner = StaticKeyInner {
140     key: atomic::ATOMIC_UINT_INIT,
141 };
142
143 static INIT_KEYS: Once = ONCE_INIT;
144 static mut KEYS: *mut Mutex<Vec<imp::Key>> = 0 as *mut _;
145
146 impl StaticKey {
147     /// Gets the value associated with this TLS key
148     ///
149     /// This will lazily allocate a TLS key from the OS if one has not already
150     /// been allocated.
151     #[inline]
152     pub unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) }
153
154     /// Sets this TLS key to a new value.
155     ///
156     /// This will lazily allocate a TLS key from the OS if one has not already
157     /// been allocated.
158     #[inline]
159     pub unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) }
160
161     /// Deallocates this OS TLS key.
162     ///
163     /// This function is unsafe as there is no guarantee that the key is not
164     /// currently in use by other threads or will not ever be used again.
165     ///
166     /// Note that this does *not* run the user-provided destructor if one was
167     /// specified at definition time. Doing so must be done manually.
168     pub unsafe fn destroy(&self) {
169         match self.inner.key.swap(0, Ordering::SeqCst) {
170             0 => {}
171             n => { imp::destroy(n as imp::Key) }
172         }
173     }
174
175     #[inline]
176     unsafe fn key(&self) -> imp::Key {
177         match self.inner.key.load(Ordering::Relaxed) {
178             0 => self.lazy_init() as imp::Key,
179             n => n as imp::Key
180         }
181     }
182
183     unsafe fn lazy_init(&self) -> uint {
184         // POSIX allows the key created here to be 0, but the compare_and_swap
185         // below relies on using 0 as a sentinel value to check who won the
186         // race to set the shared TLS key. As far as I know, there is no
187         // guaranteed value that cannot be returned as a posix_key_create key,
188         // so there is no value we can initialize the inner key with to
189         // prove that it has not yet been set. As such, we'll continue using a
190         // value of 0, but with some gyrations to make sure we have a non-0
191         // value returned from the creation routine.
192         // FIXME: this is clearly a hack, and should be cleaned up.
193         let key1 = imp::create(self.dtor);
194         let key = if key1 != 0 {
195             key1
196         } else {
197             let key2 = imp::create(self.dtor);
198             imp::destroy(key1);
199             key2
200         };
201         assert!(key != 0);
202         match self.inner.key.compare_and_swap(0, key as uint, Ordering::SeqCst) {
203             // The CAS succeeded, so we've created the actual key
204             0 => key as uint,
205             // If someone beat us to the punch, use their key instead
206             n => { imp::destroy(key); n }
207         }
208     }
209 }
210
211 impl Key {
212     /// Create a new managed OS TLS key.
213     ///
214     /// This key will be deallocated when the key falls out of scope.
215     ///
216     /// The argument provided is an optionally-specified destructor for the
217     /// value of this TLS key. When a thread exits and the value for this key
218     /// is non-null the destructor will be invoked. The TLS value will be reset
219     /// to null before the destructor is invoked.
220     ///
221     /// Note that the destructor will not be run when the `Key` goes out of
222     /// scope.
223     #[inline]
224     pub fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
225         Key { key: unsafe { imp::create(dtor) } }
226     }
227
228     /// See StaticKey::get
229     #[inline]
230     pub fn get(&self) -> *mut u8 {
231         unsafe { imp::get(self.key) }
232     }
233
234     /// See StaticKey::set
235     #[inline]
236     pub fn set(&self, val: *mut u8) {
237         unsafe { imp::set(self.key, val) }
238     }
239 }
240
241 impl Drop for Key {
242     fn drop(&mut self) {
243         unsafe { imp::destroy(self.key) }
244     }
245 }
246
247 #[cfg(test)]
248 mod tests {
249     use prelude::v1::*;
250     use super::{Key, StaticKey, INIT_INNER};
251
252     fn assert_sync<T: Sync>() {}
253     fn assert_send<T: Send>() {}
254
255     #[test]
256     fn smoke() {
257         assert_sync::<Key>();
258         assert_send::<Key>();
259
260         let k1 = Key::new(None);
261         let k2 = Key::new(None);
262         assert!(k1.get().is_null());
263         assert!(k2.get().is_null());
264         k1.set(1 as *mut _);
265         k2.set(2 as *mut _);
266         assert_eq!(k1.get() as uint, 1);
267         assert_eq!(k2.get() as uint, 2);
268     }
269
270     #[test]
271     fn statik() {
272         static K1: StaticKey = StaticKey { inner: INIT_INNER, dtor: None };
273         static K2: StaticKey = StaticKey { inner: INIT_INNER, dtor: None };
274
275         unsafe {
276             assert!(K1.get().is_null());
277             assert!(K2.get().is_null());
278             K1.set(1 as *mut _);
279             K2.set(2 as *mut _);
280             assert_eq!(K1.get() as uint, 1);
281             assert_eq!(K2.get() as uint, 2);
282         }
283     }
284 }