]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/common/thread_local.rs
std: Add a new top-level thread_local module
[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::*;
60
61 use kinds::marker;
62 use mem;
63 use rustrt::exclusive::Exclusive;
64 use rustrt;
65 use sync::atomic::{mod, AtomicUint};
66 use sync::{Once, ONCE_INIT};
67
68 use sys::thread_local as imp;
69
70 /// A type for TLS keys that are statically allocated.
71 ///
72 /// This type is entirely `unsafe` to use as it does not protect against
73 /// use-after-deallocation or use-during-deallocation.
74 ///
75 /// The actual OS-TLS key is lazily allocated when this is used for the first
76 /// time. The key is also deallocated when the Rust runtime exits or `destroy`
77 /// is called, whichever comes first.
78 ///
79 /// # Example
80 ///
81 /// ```ignore
82 /// use tls::os::{StaticKey, INIT};
83 ///
84 /// static KEY: StaticKey = INIT;
85 ///
86 /// unsafe {
87 ///     assert!(KEY.get().is_null());
88 ///     KEY.set(1 as *mut u8);
89 /// }
90 /// ```
91 pub struct StaticKey {
92     /// Inner static TLS key (internals), created with by `INIT_INNER` in this
93     /// module.
94     pub inner: StaticKeyInner,
95     /// Destructor for the TLS value.
96     ///
97     /// See `Key::new` for information about when the destructor runs and how
98     /// it runs.
99     pub dtor: Option<unsafe extern fn(*mut u8)>,
100 }
101
102 /// Inner contents of `StaticKey`, created by the `INIT_INNER` constant.
103 pub struct StaticKeyInner {
104     key: AtomicUint,
105     nc: marker::NoCopy,
106 }
107
108 /// A type for a safely managed OS-based TLS slot.
109 ///
110 /// This type allocates an OS TLS key when it is initialized and will deallocate
111 /// the key when it falls out of scope. When compared with `StaticKey`, this
112 /// type is entirely safe to use.
113 ///
114 /// Implementations will likely, however, contain unsafe code as this type only
115 /// operates on `*mut u8`, an unsafe pointer.
116 ///
117 /// # Example
118 ///
119 /// ```rust,ignore
120 /// use tls::os::Key;
121 ///
122 /// let key = Key::new(None);
123 /// assert!(key.get().is_null());
124 /// key.set(1 as *mut u8);
125 /// assert!(!key.get().is_null());
126 ///
127 /// drop(key); // deallocate this TLS slot.
128 /// ```
129 pub struct Key {
130     key: imp::Key,
131 }
132
133 /// Constant initialization value for static TLS keys.
134 ///
135 /// This value specifies no destructor by default.
136 pub const INIT: StaticKey = StaticKey {
137     inner: INIT_INNER,
138     dtor: None,
139 };
140
141 /// Constant initialization value for the inner part of static TLS keys.
142 ///
143 /// This value allows specific configuration of the destructor for a TLS key.
144 pub const INIT_INNER: StaticKeyInner = StaticKeyInner {
145     key: atomic::INIT_ATOMIC_UINT,
146     nc: marker::NoCopy,
147 };
148
149 static INIT_KEYS: Once = ONCE_INIT;
150 static mut KEYS: *mut Exclusive<Vec<imp::Key>> = 0 as *mut _;
151
152 impl StaticKey {
153     /// Gets the value associated with this TLS key
154     ///
155     /// This will lazily allocate a TLS key from the OS if one has not already
156     /// been allocated.
157     #[inline]
158     pub unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) }
159
160     /// Sets this TLS key to a new value.
161     ///
162     /// This will lazily allocate a TLS key from the OS if one has not already
163     /// been allocated.
164     #[inline]
165     pub unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) }
166
167     /// Deallocates this OS TLS key.
168     ///
169     /// This function is unsafe as there is no guarantee that the key is not
170     /// currently in use by other threads or will not ever be used again.
171     ///
172     /// Note that this does *not* run the user-provided destructor if one was
173     /// specified at definition time. Doing so must be done manually.
174     pub unsafe fn destroy(&self) {
175         match self.inner.key.swap(0, atomic::SeqCst) {
176             0 => {}
177             n => { unregister_key(n as imp::Key); imp::destroy(n as imp::Key) }
178         }
179     }
180
181     #[inline]
182     unsafe fn key(&self) -> imp::Key {
183         match self.inner.key.load(atomic::Relaxed) {
184             0 => self.lazy_init() as imp::Key,
185             n => n as imp::Key
186         }
187     }
188
189     unsafe fn lazy_init(&self) -> uint {
190         let key = imp::create(self.dtor);
191         assert!(key != 0);
192         match self.inner.key.compare_and_swap(0, key as uint, atomic::SeqCst) {
193             // The CAS succeeded, so we've created the actual key
194             0 => {
195                 register_key(key);
196                 key as uint
197             }
198             // If someone beat us to the punch, use their key instead
199             n => { imp::destroy(key); n }
200         }
201     }
202 }
203
204 impl Key {
205     /// Create a new managed OS TLS key.
206     ///
207     /// This key will be deallocated when the key falls out of scope.
208     ///
209     /// The argument provided is an optionally-specified destructor for the
210     /// value of this TLS key. When a thread exits and the value for this key
211     /// is non-null the destructor will be invoked. The TLS value will be reset
212     /// to null before the destructor is invoked.
213     ///
214     /// Note that the destructor will not be run when the `Key` goes out of
215     /// scope.
216     #[inline]
217     pub fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
218         Key { key: unsafe { imp::create(dtor) } }
219     }
220
221     /// See StaticKey::get
222     #[inline]
223     pub fn get(&self) -> *mut u8 {
224         unsafe { imp::get(self.key) }
225     }
226
227     /// See StaticKey::set
228     #[inline]
229     pub fn set(&self, val: *mut u8) {
230         unsafe { imp::set(self.key, val) }
231     }
232 }
233
234 impl Drop for Key {
235     fn drop(&mut self) {
236         unsafe { imp::destroy(self.key) }
237     }
238 }
239
240 fn init_keys() {
241     let keys = box Exclusive::new(Vec::<imp::Key>::new());
242     unsafe {
243         KEYS = mem::transmute(keys);
244     }
245
246     rustrt::at_exit(proc() unsafe {
247         let keys: Box<Exclusive<Vec<imp::Key>>> = mem::transmute(KEYS);
248         KEYS = 0 as *mut _;
249         let keys = keys.lock();
250         for key in keys.iter() {
251             imp::destroy(*key);
252         }
253     });
254 }
255
256 fn register_key(key: imp::Key) {
257     INIT_KEYS.doit(init_keys);
258     let mut keys = unsafe { (*KEYS).lock() };
259     keys.push(key);
260 }
261
262 fn unregister_key(key: imp::Key) {
263     INIT_KEYS.doit(init_keys);
264     let mut keys = unsafe { (*KEYS).lock() };
265     keys.retain(|k| *k != key);
266 }
267
268 #[cfg(test)]
269 mod tests {
270     use prelude::*;
271     use super::{Key, StaticKey, INIT_INNER};
272
273     fn assert_sync<T: Sync>() {}
274     fn assert_send<T: Send>() {}
275
276     #[test]
277     fn smoke() {
278         assert_sync::<Key>();
279         assert_send::<Key>();
280
281         let k1 = Key::new(None);
282         let k2 = Key::new(None);
283         assert!(k1.get().is_null());
284         assert!(k2.get().is_null());
285         k1.set(1 as *mut _);
286         k2.set(2 as *mut _);
287         assert_eq!(k1.get() as uint, 1);
288         assert_eq!(k2.get() as uint, 2);
289     }
290
291     #[test]
292     fn statik() {
293         static K1: StaticKey = StaticKey { inner: INIT_INNER, dtor: None };
294         static K2: StaticKey = StaticKey { inner: INIT_INNER, dtor: None };
295
296         unsafe {
297             assert!(K1.get().is_null());
298             assert!(K2.get().is_null());
299             K1.set(1 as *mut _);
300             K2.set(2 as *mut _);
301             assert_eq!(K1.get() as uint, 1);
302             assert_eq!(K2.get() as uint, 2);
303         }
304     }
305 }
306