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 //! 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 stor 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);
45 // macro hygiene sure would be nice, wouldn't it?
46 #[doc(hidden)] pub use self::imp::KeyInner;
47 #[doc(hidden)] pub use sys_common::thread_local::INIT as OS_INIT;
49 /// Type representing a thread local storage key corresponding to a reference
50 /// to the type parameter `T`.
52 /// Keys are statically allocated and can contain a reference to an instance of
53 /// type `T` scoped to a particular lifetime. Keys provides two methods, `set`
54 /// and `with`, both of which currently use closures to control the scope of
56 pub struct Key<T> { #[doc(hidden)] pub inner: KeyInner<T> }
58 /// Declare a new scoped thread local storage key.
60 /// This macro declares a `static` item on which methods are used to get and
61 /// set the value stored within.
63 macro_rules! scoped_thread_local(
64 (static $name:ident: $t:ty) => (
65 __scoped_thread_local_inner!(static $name: $t)
67 (pub static $name:ident: $t:ty) => (
68 __scoped_thread_local_inner!(pub static $name: $t)
74 macro_rules! __scoped_thread_local_inner(
75 (static $name:ident: $t:ty) => (
76 #[cfg_attr(not(any(windows, target_os = "android", target_os = "ios")),
78 static $name: ::std::thread_local::scoped::Key<$t> =
79 __scoped_thread_local_inner!($t);
81 (pub static $name:ident: $t:ty) => (
82 #[cfg_attr(not(any(windows, target_os = "android", target_os = "ios")),
84 pub static $name: ::std::thread_local::scoped::Key<$t> =
85 __scoped_thread_local_inner!($t);
88 use std::thread_local::scoped::Key as __Key;
90 #[cfg(not(any(windows, target_os = "android", target_os = "ios")))]
91 const INIT: __Key<$t> = __Key {
92 inner: ::std::thread_local::scoped::KeyInner {
93 inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
97 #[cfg(any(windows, target_os = "android", target_os = "ios"))]
98 const INIT: __Key<$t> = __Key {
99 inner: ::std::thread_local::scoped::KeyInner {
100 inner: ::std::thread_local::scoped::OS_INIT,
101 marker: ::std::kinds::marker::InvariantType,
110 /// Insert a value into this scoped thread local storage slot for a
111 /// duration of a closure.
113 /// While `cb` is running, the value `t` will be returned by `get` unless
114 /// this function is called recursively inside of `cb`.
116 /// Upon return, this function will restore the previous value, if any
122 /// scoped_thread_local!(static FOO: uint)
124 /// FOO.set(&100, || {
125 /// let val = FOO.with(|v| *v);
126 /// assert_eq!(val, 100);
128 /// // set can be called recursively
129 /// FOO.set(&101, || {
133 /// // Recursive calls restore the previous value.
134 /// let val = FOO.with(|v| *v);
135 /// assert_eq!(val, 100);
138 pub fn set<R>(&'static self, t: &T, cb: || -> R) -> R {
139 struct Reset<'a, T: 'a> {
140 key: &'a KeyInner<T>,
144 impl<'a, T> Drop for Reset<'a, T> {
146 unsafe { self.key.set(self.val) }
151 let prev = self.inner.get();
152 self.inner.set(t as *const T as *mut T);
156 let _reset = Reset { key: &self.inner, val: prev };
160 /// Get a value out of this scoped variable.
162 /// This function takes a closure which receives the value of this
167 /// This function will panic if `set` has not previously been called.
172 /// scoped_thread_local!(static FOO: uint)
174 /// FOO.with(|slot| {
175 /// // work with `slot`
178 pub fn with<R>(&'static self, cb: |&T| -> R) -> R {
180 let ptr = self.inner.get();
181 assert!(!ptr.is_null(), "cannot access a scoped thread local \
182 variable without calling `set` first");
187 /// Test whether this TLS key has been `set` for the current thread.
188 pub fn is_set(&'static self) -> bool {
189 unsafe { !self.inner.get().is_null() }
193 #[cfg(not(any(windows, target_os = "android", target_os = "ios")))]
195 use std::cell::UnsafeCell;
197 // FIXME: Should be a `Cell`, but that's not `Sync`
199 pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
202 impl<T> KeyInner<T> {
204 pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
206 pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
210 #[cfg(any(windows, target_os = "android", target_os = "ios"))]
213 use sys_common::thread_local::StaticKey as OsStaticKey;
216 pub struct KeyInner<T> {
217 pub inner: OsStaticKey,
218 pub marker: marker::InvariantType<T>,
222 impl<T> KeyInner<T> {
224 pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
226 pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
238 scoped_thread_local!(static BAR: uint)
240 assert!(!BAR.is_set());
242 assert!(BAR.is_set());
244 assert_eq!(*slot, 1);
247 assert!(!BAR.is_set());
252 scoped_thread_local!(static BAR: Cell<uint>)
254 BAR.set(&Cell::new(1), || {
256 assert_eq!(slot.get(), 1);