]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys_common/thread_local.rs
New upstream version 1.14.0+dfsg1
[rustc.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 //! ```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 #![unstable(feature = "thread_local_internals", issue = "0")]
59 #![allow(dead_code)] // sys isn't exported yet
60
61 use sync::atomic::{self, AtomicUsize, Ordering};
62
63 use sys::thread_local as imp;
64
65 /// A type for TLS keys that are statically allocated.
66 ///
67 /// This type is entirely `unsafe` to use as it does not protect against
68 /// use-after-deallocation or use-during-deallocation.
69 ///
70 /// The actual OS-TLS key is lazily allocated when this is used for the first
71 /// time. The key is also deallocated when the Rust runtime exits or `destroy`
72 /// is called, whichever comes first.
73 ///
74 /// # Examples
75 ///
76 /// ```ignore
77 /// use tls::os::{StaticKey, INIT};
78 ///
79 /// static KEY: StaticKey = INIT;
80 ///
81 /// unsafe {
82 /// assert!(KEY.get().is_null());
83 /// KEY.set(1 as *mut u8);
84 /// }
85 /// ```
86 pub struct StaticKey {
87 /// Inner static TLS key (internals).
88 key: AtomicUsize,
89 /// Destructor for the TLS value.
90 ///
91 /// See `Key::new` for information about when the destructor runs and how
92 /// it runs.
93 dtor: Option<unsafe extern fn(*mut u8)>,
94 }
95
96 /// A type for a safely managed OS-based TLS slot.
97 ///
98 /// This type allocates an OS TLS key when it is initialized and will deallocate
99 /// the key when it falls out of scope. When compared with `StaticKey`, this
100 /// type is entirely safe to use.
101 ///
102 /// Implementations will likely, however, contain unsafe code as this type only
103 /// operates on `*mut u8`, a raw pointer.
104 ///
105 /// # Examples
106 ///
107 /// ```rust,ignore
108 /// use tls::os::Key;
109 ///
110 /// let key = Key::new(None);
111 /// assert!(key.get().is_null());
112 /// key.set(1 as *mut u8);
113 /// assert!(!key.get().is_null());
114 ///
115 /// drop(key); // deallocate this TLS slot.
116 /// ```
117 pub struct Key {
118 key: imp::Key,
119 }
120
121 /// Constant initialization value for static TLS keys.
122 ///
123 /// This value specifies no destructor by default.
124 pub const INIT: StaticKey = StaticKey::new(None);
125
126 impl StaticKey {
127 pub const fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> StaticKey {
128 StaticKey {
129 key: atomic::AtomicUsize::new(0),
130 dtor: dtor
131 }
132 }
133
134 /// Gets the value associated with this TLS key
135 ///
136 /// This will lazily allocate a TLS key from the OS if one has not already
137 /// been allocated.
138 #[inline]
139 pub unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) }
140
141 /// Sets this TLS key to a new value.
142 ///
143 /// This will lazily allocate a TLS key from the OS if one has not already
144 /// been allocated.
145 #[inline]
146 pub unsafe fn set(&self, val: *mut u8) { imp::set(self.key(), val) }
147
148 /// Deallocates this OS TLS key.
149 ///
150 /// This function is unsafe as there is no guarantee that the key is not
151 /// currently in use by other threads or will not ever be used again.
152 ///
153 /// Note that this does *not* run the user-provided destructor if one was
154 /// specified at definition time. Doing so must be done manually.
155 pub unsafe fn destroy(&self) {
156 match self.key.swap(0, Ordering::SeqCst) {
157 0 => {}
158 n => { imp::destroy(n as imp::Key) }
159 }
160 }
161
162 #[inline]
163 unsafe fn key(&self) -> imp::Key {
164 match self.key.load(Ordering::Relaxed) {
165 0 => self.lazy_init() as imp::Key,
166 n => n as imp::Key
167 }
168 }
169
170 unsafe fn lazy_init(&self) -> usize {
171 // POSIX allows the key created here to be 0, but the compare_and_swap
172 // below relies on using 0 as a sentinel value to check who won the
173 // race to set the shared TLS key. As far as I know, there is no
174 // guaranteed value that cannot be returned as a posix_key_create key,
175 // so there is no value we can initialize the inner key with to
176 // prove that it has not yet been set. As such, we'll continue using a
177 // value of 0, but with some gyrations to make sure we have a non-0
178 // value returned from the creation routine.
179 // FIXME: this is clearly a hack, and should be cleaned up.
180 let key1 = imp::create(self.dtor);
181 let key = if key1 != 0 {
182 key1
183 } else {
184 let key2 = imp::create(self.dtor);
185 imp::destroy(key1);
186 key2
187 };
188 assert!(key != 0);
189 match self.key.compare_and_swap(0, key as usize, Ordering::SeqCst) {
190 // The CAS succeeded, so we've created the actual key
191 0 => key as usize,
192 // If someone beat us to the punch, use their key instead
193 n => { imp::destroy(key); n }
194 }
195 }
196 }
197
198 impl Key {
199 /// Creates a new managed OS TLS key.
200 ///
201 /// This key will be deallocated when the key falls out of scope.
202 ///
203 /// The argument provided is an optionally-specified destructor for the
204 /// value of this TLS key. When a thread exits and the value for this key
205 /// is non-null the destructor will be invoked. The TLS value will be reset
206 /// to null before the destructor is invoked.
207 ///
208 /// Note that the destructor will not be run when the `Key` goes out of
209 /// scope.
210 #[inline]
211 pub fn new(dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
212 Key { key: unsafe { imp::create(dtor) } }
213 }
214
215 /// See StaticKey::get
216 #[inline]
217 pub fn get(&self) -> *mut u8 {
218 unsafe { imp::get(self.key) }
219 }
220
221 /// See StaticKey::set
222 #[inline]
223 pub fn set(&self, val: *mut u8) {
224 unsafe { imp::set(self.key, val) }
225 }
226 }
227
228 impl Drop for Key {
229 fn drop(&mut self) {
230 unsafe { imp::destroy(self.key) }
231 }
232 }
233
234 #[cfg(test)]
235 mod tests {
236 use super::{Key, StaticKey};
237
238 fn assert_sync<T: Sync>() {}
239 fn assert_send<T: Send>() {}
240
241 #[test]
242 fn smoke() {
243 assert_sync::<Key>();
244 assert_send::<Key>();
245
246 let k1 = Key::new(None);
247 let k2 = Key::new(None);
248 assert!(k1.get().is_null());
249 assert!(k2.get().is_null());
250 k1.set(1 as *mut _);
251 k2.set(2 as *mut _);
252 assert_eq!(k1.get() as usize, 1);
253 assert_eq!(k2.get() as usize, 2);
254 }
255
256 #[test]
257 fn statik() {
258 static K1: StaticKey = StaticKey::new(None);
259 static K2: StaticKey = StaticKey::new(None);
260
261 unsafe {
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 usize, 1);
267 assert_eq!(K2.get() as usize, 2);
268 }
269 }
270 }