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