1 //! OS-based thread local storage
3 //! This module provides an implementation of OS-based thread local storage,
4 //! using the native OS-provided facilities (think `TlsAlloc` or
5 //! `pthread_setspecific`). The interface of this differs from the other types
6 //! of thread-local-storage provided in this crate in that OS-based TLS can only
7 //! get/set pointer-sized data, possibly with an associated destructor.
9 //! This module also provides two flavors of TLS. One is intended for static
10 //! initialization, and does not contain a `Drop` implementation to deallocate
11 //! the OS-TLS key. The other is a type which does implement `Drop` and hence
12 //! has a safe interface.
16 //! This module should likely not be used directly unless other primitives are
17 //! being built on. Types such as `thread_local::spawn::Key` are likely much
18 //! more useful in practice than this OS-based version which likely requires
19 //! unsafe code to interoperate with.
23 //! Using a dynamically allocated TLS key. Note that this key can be shared
24 //! among many threads via an `Arc`.
26 //! ```ignore (cannot-doctest-private-modules)
27 //! let key = Key::new(None);
28 //! assert!(key.get().is_null());
29 //! key.set(1 as *mut u8);
30 //! assert!(!key.get().is_null());
32 //! drop(key); // deallocate this TLS slot.
35 //! Sometimes a statically allocated key is either required or easier to work
38 //! ```ignore (cannot-doctest-private-modules)
39 //! static KEY: StaticKey = INIT;
42 //! assert!(KEY.get().is_null());
43 //! KEY.set(1 as *mut u8);
47 #![allow(non_camel_case_types)]
48 #![unstable(feature = "thread_local_internals", issue = "none")]
54 use crate::sync::atomic::{self, AtomicUsize, Ordering};
55 use crate::sys::thread_local_key as imp;
57 /// A type for TLS keys that are statically allocated.
59 /// This type is entirely `unsafe` to use as it does not protect against
60 /// use-after-deallocation or use-during-deallocation.
62 /// The actual OS-TLS key is lazily allocated when this is used for the first
63 /// time. The key is also deallocated when the Rust runtime exits or `destroy`
64 /// is called, whichever comes first.
68 /// ```ignore (cannot-doctest-private-modules)
69 /// use tls::os::{StaticKey, INIT};
71 /// // Use a regular global static to store the key.
72 /// static KEY: StaticKey = INIT;
74 /// // The state provided via `get` and `set` is thread-local.
76 /// assert!(KEY.get().is_null());
77 /// KEY.set(1 as *mut u8);
80 pub struct StaticKey {
81 /// Inner static TLS key (internals).
83 /// Destructor for the TLS value.
85 /// See `Key::new` for information about when the destructor runs and how
87 dtor: Option<unsafe extern "C" fn(*mut u8)>,
90 /// A type for a safely managed OS-based TLS slot.
92 /// This type allocates an OS TLS key when it is initialized and will deallocate
93 /// the key when it falls out of scope. When compared with `StaticKey`, this
94 /// type is entirely safe to use.
96 /// Implementations will likely, however, contain unsafe code as this type only
97 /// operates on `*mut u8`, a raw pointer.
101 /// ```ignore (cannot-doctest-private-modules)
102 /// use tls::os::Key;
104 /// let key = Key::new(None);
105 /// assert!(key.get().is_null());
106 /// key.set(1 as *mut u8);
107 /// assert!(!key.get().is_null());
109 /// drop(key); // deallocate this TLS slot.
115 /// Constant initialization value for static TLS keys.
117 /// This value specifies no destructor by default.
118 pub const INIT: StaticKey = StaticKey::new(None);
121 #[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
122 pub const fn new(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> StaticKey {
123 StaticKey { key: atomic::AtomicUsize::new(0), dtor }
126 /// Gets the value associated with this TLS key
128 /// This will lazily allocate a TLS key from the OS if one has not already
131 pub unsafe fn get(&self) -> *mut u8 {
135 /// Sets this TLS key to a new value.
137 /// This will lazily allocate a TLS key from the OS if one has not already
140 pub unsafe fn set(&self, val: *mut u8) {
141 imp::set(self.key(), val)
145 unsafe fn key(&self) -> imp::Key {
146 match self.key.load(Ordering::Relaxed) {
147 0 => self.lazy_init() as imp::Key,
152 unsafe fn lazy_init(&self) -> usize {
153 // POSIX allows the key created here to be 0, but the compare_exchange
154 // below relies on using 0 as a sentinel value to check who won the
155 // race to set the shared TLS key. As far as I know, there is no
156 // guaranteed value that cannot be returned as a posix_key_create key,
157 // so there is no value we can initialize the inner key with to
158 // prove that it has not yet been set. As such, we'll continue using a
159 // value of 0, but with some gyrations to make sure we have a non-0
160 // value returned from the creation routine.
161 // FIXME: this is clearly a hack, and should be cleaned up.
162 let key1 = imp::create(self.dtor);
163 let key = if key1 != 0 {
166 let key2 = imp::create(self.dtor);
171 match self.key.compare_exchange(0, key as usize, Ordering::SeqCst, Ordering::SeqCst) {
172 // The CAS succeeded, so we've created the actual key
173 Ok(_) => key as usize,
174 // If someone beat us to the punch, use their key instead
184 /// Creates a new managed OS TLS key.
186 /// This key will be deallocated when the key falls out of scope.
188 /// The argument provided is an optionally-specified destructor for the
189 /// value of this TLS key. When a thread exits and the value for this key
190 /// is non-null the destructor will be invoked. The TLS value will be reset
191 /// to null before the destructor is invoked.
193 /// Note that the destructor will not be run when the `Key` goes out of
196 pub fn new(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> Key {
197 Key { key: unsafe { imp::create(dtor) } }
200 /// See StaticKey::get
202 pub fn get(&self) -> *mut u8 {
203 unsafe { imp::get(self.key) }
206 /// See StaticKey::set
208 pub fn set(&self, val: *mut u8) {
209 unsafe { imp::set(self.key, val) }
215 unsafe { imp::destroy(self.key) }