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);
41 #![unstable = "scoped TLS has yet to have wide enough use to fully consider \
42 stabilizing its interface"]
46 // macro hygiene sure would be nice, wouldn't it?
49 pub use super::imp::KeyInner;
50 pub use sys_common::thread_local::INIT as OS_INIT;
53 /// Type representing a thread local storage key corresponding to a reference
54 /// to the type parameter `T`.
56 /// Keys are statically allocated and can contain a reference to an instance of
57 /// type `T` scoped to a particular lifetime. Keys provides two methods, `set`
58 /// and `with`, both of which currently use closures to control the scope of
60 pub struct Key<T> { #[doc(hidden)] pub inner: __impl::KeyInner<T> }
62 /// Declare a new scoped thread local storage key.
64 /// This macro declares a `static` item on which methods are used to get and
65 /// set the value stored within.
67 macro_rules! scoped_thread_local {
68 (static $name:ident: $t:ty) => (
69 __scoped_thread_local_inner!(static $name: $t);
71 (pub static $name:ident: $t:ty) => (
72 __scoped_thread_local_inner!(pub static $name: $t);
78 macro_rules! __scoped_thread_local_inner {
79 (static $name:ident: $t:ty) => (
80 #[cfg_attr(not(any(windows,
81 target_os = "android",
83 target_arch = "aarch64")),
85 static $name: ::std::thread_local::scoped::Key<$t> =
86 __scoped_thread_local_inner!($t);
88 (pub static $name:ident: $t:ty) => (
89 #[cfg_attr(not(any(windows,
90 target_os = "android",
92 target_arch = "aarch64")),
94 pub static $name: ::std::thread_local::scoped::Key<$t> =
95 __scoped_thread_local_inner!($t);
98 use std::thread_local::scoped::Key as __Key;
100 #[cfg(not(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64")))]
101 const _INIT: __Key<$t> = __Key {
102 inner: ::std::thread_local::scoped::__impl::KeyInner {
103 inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
107 #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))]
108 const _INIT: __Key<$t> = __Key {
109 inner: ::std::thread_local::scoped::__impl::KeyInner {
110 inner: ::std::thread_local::scoped::__impl::OS_INIT,
111 marker: ::std::kinds::marker::InvariantType,
120 /// Insert a value into this scoped thread local storage slot for a
121 /// duration of a closure.
123 /// While `cb` is running, the value `t` will be returned by `get` unless
124 /// this function is called recursively inside of `cb`.
126 /// Upon return, this function will restore the previous value, if any
132 /// scoped_thread_local!(static FOO: uint);
134 /// FOO.set(&100, || {
135 /// let val = FOO.with(|v| *v);
136 /// assert_eq!(val, 100);
138 /// // set can be called recursively
139 /// FOO.set(&101, || {
143 /// // Recursive calls restore the previous value.
144 /// let val = FOO.with(|v| *v);
145 /// assert_eq!(val, 100);
148 pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
151 struct Reset<'a, T: 'a> {
152 key: &'a __impl::KeyInner<T>,
156 impl<'a, T> Drop for Reset<'a, T> {
158 unsafe { self.key.set(self.val) }
163 let prev = self.inner.get();
164 self.inner.set(t as *const T as *mut T);
168 let _reset = Reset { key: &self.inner, val: prev };
172 /// Get a value out of this scoped variable.
174 /// This function takes a closure which receives the value of this
179 /// This function will panic if `set` has not previously been called.
184 /// scoped_thread_local!(static FOO: uint);
186 /// FOO.with(|slot| {
187 /// // work with `slot`
190 pub fn with<R, F>(&'static self, cb: F) -> R where
194 let ptr = self.inner.get();
195 assert!(!ptr.is_null(), "cannot access a scoped thread local \
196 variable without calling `set` first");
201 /// Test whether this TLS key has been `set` for the current thread.
202 pub fn is_set(&'static self) -> bool {
203 unsafe { !self.inner.get().is_null() }
207 #[cfg(not(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64")))]
209 use std::cell::UnsafeCell;
212 pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
214 unsafe impl<T> ::kinds::Sync for KeyInner<T> { }
217 impl<T> KeyInner<T> {
219 pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
221 pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
225 #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))]
228 use sys_common::thread_local::StaticKey as OsStaticKey;
231 pub struct KeyInner<T> {
232 pub inner: OsStaticKey,
233 pub marker: marker::InvariantType<T>,
236 unsafe impl<T> ::kinds::Sync for KeyInner<T> { }
239 impl<T> KeyInner<T> {
241 pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
243 pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
253 scoped_thread_local!(static FOO: uint);
257 scoped_thread_local!(static BAR: uint);
259 assert!(!BAR.is_set());
261 assert!(BAR.is_set());
263 assert_eq!(*slot, 1);
266 assert!(!BAR.is_set());
271 scoped_thread_local!(static BAR: Cell<uint>);
273 BAR.set(&Cell::new(1), || {
275 assert_eq!(slot.get(), 1);
281 fn scope_item_allowed() {
282 assert!(!FOO.is_set());
284 assert!(FOO.is_set());
286 assert_eq!(*slot, 1);
289 assert!(!FOO.is_set());