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.
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.
11 //! OS-based thread local storage
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
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.
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.
33 //! Using a dynamically allocated TLS key. Note that this key can be shared
34 //! among many threads via an `Arc`.
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());
42 //! drop(key); // deallocate this TLS slot.
45 //! Sometimes a statically allocated key is either required or easier to work
49 //! static KEY: StaticKey = INIT;
52 //! assert!(KEY.get().is_null());
53 //! KEY.set(1 as *mut u8);
57 #![allow(non_camel_case_types)]
58 #![unstable(feature = "thread_local_internals")]
59 #![allow(dead_code)] // sys isn't exported yet
63 use sync
::atomic
::{self, AtomicUsize, Ordering}
;
65 use sys
::thread_local
as imp
;
67 /// A type for TLS keys that are statically allocated.
69 /// This type is entirely `unsafe` to use as it does not protect against
70 /// use-after-deallocation or use-during-deallocation.
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.
79 /// use tls::os::{StaticKey, INIT};
81 /// static KEY: StaticKey = INIT;
84 /// assert!(KEY.get().is_null());
85 /// KEY.set(1 as *mut u8);
88 pub struct StaticKey
{
89 /// Inner static TLS key (internals), created with by `INIT_INNER` in this
91 pub inner
: StaticKeyInner
,
92 /// Destructor for the TLS value.
94 /// See `Key::new` for information about when the destructor runs and how
96 pub dtor
: Option
<unsafe extern fn(*mut u8)>,
99 /// Inner contents of `StaticKey`, created by the `INIT_INNER` constant.
100 pub struct StaticKeyInner
{
104 /// A type for a safely managed OS-based TLS slot.
106 /// This type allocates an OS TLS key when it is initialized and will deallocate
107 /// the key when it falls out of scope. When compared with `StaticKey`, this
108 /// type is entirely safe to use.
110 /// Implementations will likely, however, contain unsafe code as this type only
111 /// operates on `*mut u8`, an unsafe pointer.
116 /// use tls::os::Key;
118 /// let key = Key::new(None);
119 /// assert!(key.get().is_null());
120 /// key.set(1 as *mut u8);
121 /// assert!(!key.get().is_null());
123 /// drop(key); // deallocate this TLS slot.
129 /// Constant initialization value for static TLS keys.
131 /// This value specifies no destructor by default.
132 pub const INIT
: StaticKey
= StaticKey
{
137 /// Constant initialization value for the inner part of static TLS keys.
139 /// This value allows specific configuration of the destructor for a TLS key.
140 pub const INIT_INNER
: StaticKeyInner
= StaticKeyInner
{
141 key
: atomic
::ATOMIC_USIZE_INIT
,
145 /// Gets the value associated with this TLS key
147 /// This will lazily allocate a TLS key from the OS if one has not already
150 pub unsafe fn get(&self) -> *mut u8 { imp::get(self.key()) }
152 /// Sets this TLS key to a new value.
154 /// This will lazily allocate a TLS key from the OS if one has not already
157 pub unsafe fn set(&self, val
: *mut u8) { imp::set(self.key(), val) }
159 /// Deallocates this OS TLS key.
161 /// This function is unsafe as there is no guarantee that the key is not
162 /// currently in use by other threads or will not ever be used again.
164 /// Note that this does *not* run the user-provided destructor if one was
165 /// specified at definition time. Doing so must be done manually.
166 pub unsafe fn destroy(&self) {
167 match self.inner
.key
.swap(0, Ordering
::SeqCst
) {
169 n
=> { imp::destroy(n as imp::Key) }
174 unsafe fn key(&self) -> imp
::Key
{
175 match self.inner
.key
.load(Ordering
::Relaxed
) {
176 0 => self.lazy_init() as imp
::Key
,
181 unsafe fn lazy_init(&self) -> usize {
182 // POSIX allows the key created here to be 0, but the compare_and_swap
183 // below relies on using 0 as a sentinel value to check who won the
184 // race to set the shared TLS key. As far as I know, there is no
185 // guaranteed value that cannot be returned as a posix_key_create key,
186 // so there is no value we can initialize the inner key with to
187 // prove that it has not yet been set. As such, we'll continue using a
188 // value of 0, but with some gyrations to make sure we have a non-0
189 // value returned from the creation routine.
190 // FIXME: this is clearly a hack, and should be cleaned up.
191 let key1
= imp
::create(self.dtor
);
192 let key
= if key1
!= 0 {
195 let key2
= imp
::create(self.dtor
);
200 match self.inner
.key
.compare_and_swap(0, key
as usize, Ordering
::SeqCst
) {
201 // The CAS succeeded, so we've created the actual key
203 // If someone beat us to the punch, use their key instead
204 n
=> { imp::destroy(key); n }
210 /// Creates a new managed OS TLS key.
212 /// This key will be deallocated when the key falls out of scope.
214 /// The argument provided is an optionally-specified destructor for the
215 /// value of this TLS key. When a thread exits and the value for this key
216 /// is non-null the destructor will be invoked. The TLS value will be reset
217 /// to null before the destructor is invoked.
219 /// Note that the destructor will not be run when the `Key` goes out of
222 pub fn new(dtor
: Option
<unsafe extern fn(*mut u8)>) -> Key
{
223 Key { key: unsafe { imp::create(dtor) }
}
226 /// See StaticKey::get
228 pub fn get(&self) -> *mut u8 {
229 unsafe { imp::get(self.key) }
232 /// See StaticKey::set
234 pub fn set(&self, val
: *mut u8) {
235 unsafe { imp::set(self.key, val) }
241 unsafe { imp::destroy(self.key) }
248 use super::{Key, StaticKey, INIT_INNER}
;
250 fn assert_sync
<T
: Sync
>() {}
251 fn assert_send
<T
: Send
>() {}
255 assert_sync
::<Key
>();
256 assert_send
::<Key
>();
258 let k1
= Key
::new(None
);
259 let k2
= Key
::new(None
);
260 assert
!(k1
.get().is_null());
261 assert
!(k2
.get().is_null());
264 assert_eq
!(k1
.get() as usize, 1);
265 assert_eq
!(k2
.get() as usize, 2);
270 static K1
: StaticKey
= StaticKey { inner: INIT_INNER, dtor: None }
;
271 static K2
: StaticKey
= StaticKey { inner: INIT_INNER, dtor: None }
;
274 assert
!(K1
.get().is_null());
275 assert
!(K2
.get().is_null());
278 assert_eq
!(K1
.get() as usize, 1);
279 assert_eq
!(K2
.get() as usize, 2);