1 // Copyright 2014-2015 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 //! Scoped thread-local storage
13 //! This module provides the ability to generate *scoped* thread-local
14 //! variables. In this sense, scoped indicates that thread local storage
15 //! actually stores a reference to a value, and this reference is only placed
16 //! in storage for a scoped amount of time.
18 //! There are no restrictions on what types can be placed into a scoped
19 //! variable, but all scoped variables are initialized to the equivalent of
20 //! null. Scoped thread local storage is useful when a value is present for a known
21 //! period of time and it is not required to relinquish ownership of the
27 //! scoped_thread_local!(static FOO: uint);
29 //! // Initially each scoped slot is empty.
30 //! assert!(!FOO.is_set());
32 //! // When inserting a value, the value is only in place for the duration
33 //! // of the closure specified.
36 //! assert_eq!(*slot, 1);
42 #![unstable = "scoped TLS has yet to have wide enough use to fully consider \
43 stabilizing its interface"]
47 // macro hygiene sure would be nice, wouldn't it?
50 pub use super::imp::KeyInner;
51 pub use sys_common::thread_local::INIT as OS_INIT;
54 /// Type representing a thread local storage key corresponding to a reference
55 /// to the type parameter `T`.
57 /// Keys are statically allocated and can contain a reference to an instance of
58 /// type `T` scoped to a particular lifetime. Keys provides two methods, `set`
59 /// and `with`, both of which currently use closures to control the scope of
61 pub struct Key<T> { #[doc(hidden)] pub inner: __impl::KeyInner<T> }
63 /// Declare a new scoped thread local storage key.
65 /// This macro declares a `static` item on which methods are used to get and
66 /// set the value stored within.
68 macro_rules! scoped_thread_local {
69 (static $name:ident: $t:ty) => (
70 __scoped_thread_local_inner!(static $name: $t);
72 (pub static $name:ident: $t:ty) => (
73 __scoped_thread_local_inner!(pub static $name: $t);
79 macro_rules! __scoped_thread_local_inner {
80 (static $name:ident: $t:ty) => (
81 #[cfg_attr(not(any(windows,
82 target_os = "android",
84 target_arch = "aarch64")),
86 static $name: ::std::thread_local::scoped::Key<$t> =
87 __scoped_thread_local_inner!($t);
89 (pub static $name:ident: $t:ty) => (
90 #[cfg_attr(not(any(windows,
91 target_os = "android",
93 target_arch = "aarch64")),
95 pub static $name: ::std::thread_local::scoped::Key<$t> =
96 __scoped_thread_local_inner!($t);
99 use std::thread_local::scoped::Key as __Key;
101 #[cfg(not(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64")))]
102 const _INIT: __Key<$t> = __Key {
103 inner: ::std::thread_local::scoped::__impl::KeyInner {
104 inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
108 #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))]
109 const _INIT: __Key<$t> = __Key {
110 inner: ::std::thread_local::scoped::__impl::KeyInner {
111 inner: ::std::thread_local::scoped::__impl::OS_INIT,
112 marker: ::std::kinds::marker::InvariantType,
121 /// Insert a value into this scoped thread local storage slot for a
122 /// duration of a closure.
124 /// While `cb` is running, the value `t` will be returned by `get` unless
125 /// this function is called recursively inside of `cb`.
127 /// Upon return, this function will restore the previous value, if any
133 /// scoped_thread_local!(static FOO: uint);
135 /// FOO.set(&100, || {
136 /// let val = FOO.with(|v| *v);
137 /// assert_eq!(val, 100);
139 /// // set can be called recursively
140 /// FOO.set(&101, || {
144 /// // Recursive calls restore the previous value.
145 /// let val = FOO.with(|v| *v);
146 /// assert_eq!(val, 100);
149 pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
152 struct Reset<'a, T: 'a> {
153 key: &'a __impl::KeyInner<T>,
157 impl<'a, T> Drop for Reset<'a, T> {
159 unsafe { self.key.set(self.val) }
164 let prev = self.inner.get();
165 self.inner.set(t as *const T as *mut T);
169 let _reset = Reset { key: &self.inner, val: prev };
173 /// Get a value out of this scoped variable.
175 /// This function takes a closure which receives the value of this
180 /// This function will panic if `set` has not previously been called.
185 /// scoped_thread_local!(static FOO: uint);
187 /// FOO.with(|slot| {
188 /// // work with `slot`
191 pub fn with<R, F>(&'static self, cb: F) -> R where
195 let ptr = self.inner.get();
196 assert!(!ptr.is_null(), "cannot access a scoped thread local \
197 variable without calling `set` first");
202 /// Test whether this TLS key has been `set` for the current thread.
203 pub fn is_set(&'static self) -> bool {
204 unsafe { !self.inner.get().is_null() }
208 #[cfg(not(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64")))]
210 use std::cell::UnsafeCell;
213 pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
215 unsafe impl<T> ::kinds::Sync for KeyInner<T> { }
218 impl<T> KeyInner<T> {
220 pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
222 pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
226 #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))]
229 use sys_common::thread_local::StaticKey as OsStaticKey;
232 pub struct KeyInner<T> {
233 pub inner: OsStaticKey,
234 pub marker: marker::InvariantType<T>,
237 unsafe impl<T> ::kinds::Sync for KeyInner<T> { }
240 impl<T> KeyInner<T> {
242 pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
244 pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
254 scoped_thread_local!(static FOO: uint);
258 scoped_thread_local!(static BAR: uint);
260 assert!(!BAR.is_set());
262 assert!(BAR.is_set());
264 assert_eq!(*slot, 1);
267 assert!(!BAR.is_set());
272 scoped_thread_local!(static BAR: Cell<uint>);
274 BAR.set(&Cell::new(1), || {
276 assert_eq!(slot.get(), 1);
282 fn scope_item_allowed() {
283 assert!(!FOO.is_set());
285 assert!(FOO.is_set());
287 assert_eq!(*slot, 1);
290 assert!(!FOO.is_set());