]> git.proxmox.com Git - rustc.git/blob - src/libstd/thread/scoped_tls.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / libstd / thread / scoped_tls.rs
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.
4 //
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.
10
11 //! Scoped thread-local storage
12 //!
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.
17 //!
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
22 //! contents.
23 //!
24 //! # Examples
25 //!
26 //! ```
27 //! # #![feature(scoped_tls)]
28 //! scoped_thread_local!(static FOO: u32);
29 //!
30 //! // Initially each scoped slot is empty.
31 //! assert!(!FOO.is_set());
32 //!
33 //! // When inserting a value, the value is only in place for the duration
34 //! // of the closure specified.
35 //! FOO.set(&1, || {
36 //! FOO.with(|slot| {
37 //! assert_eq!(*slot, 1);
38 //! });
39 //! });
40 //! ```
41
42 #![unstable(feature = "thread_local_internals")]
43
44 use prelude::v1::*;
45
46 // macro hygiene sure would be nice, wouldn't it?
47 #[doc(hidden)]
48 pub mod __impl {
49 pub use super::imp::KeyInner;
50 pub use sys_common::thread_local::INIT as OS_INIT;
51 }
52
53 /// Type representing a thread local storage key corresponding to a reference
54 /// to the type parameter `T`.
55 ///
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
59 /// their contents.
60 #[unstable(feature = "scoped_tls",
61 reason = "scoped TLS has yet to have wide enough use to fully consider \
62 stabilizing its interface")]
63 pub struct ScopedKey<T> { #[doc(hidden)] pub inner: __impl::KeyInner<T> }
64
65 /// Declare a new scoped thread local storage key.
66 ///
67 /// This macro declares a `static` item on which methods are used to get and
68 /// set the value stored within.
69 ///
70 /// See [ScopedKey documentation](thread/struct.ScopedKey.html) for more
71 /// information.
72 #[macro_export]
73 #[allow_internal_unstable]
74 #[cfg(not(no_elf_tls))]
75 macro_rules! scoped_thread_local {
76 (static $name:ident: $t:ty) => (
77 __scoped_thread_local_inner!(static $name: $t);
78 );
79 (pub static $name:ident: $t:ty) => (
80 __scoped_thread_local_inner!(pub static $name: $t);
81 );
82 }
83
84 #[macro_export]
85 #[doc(hidden)]
86 #[allow_internal_unstable]
87 macro_rules! __scoped_thread_local_inner {
88 (static $name:ident: $t:ty) => (
89 #[cfg_attr(not(any(windows,
90 target_os = "android",
91 target_os = "ios",
92 target_os = "openbsd",
93 target_arch = "aarch64")),
94 thread_local)]
95 static $name: ::std::thread::ScopedKey<$t> =
96 __scoped_thread_local_inner!($t);
97 );
98 (pub static $name:ident: $t:ty) => (
99 #[cfg_attr(not(any(windows,
100 target_os = "android",
101 target_os = "ios",
102 target_os = "openbsd",
103 target_arch = "aarch64")),
104 thread_local)]
105 pub static $name: ::std::thread::ScopedKey<$t> =
106 __scoped_thread_local_inner!($t);
107 );
108 ($t:ty) => ({
109 use std::thread::ScopedKey as __Key;
110
111 #[cfg(not(any(windows,
112 target_os = "android",
113 target_os = "ios",
114 target_os = "openbsd",
115 target_arch = "aarch64")))]
116 const _INIT: __Key<$t> = __Key {
117 inner: ::std::thread::__scoped::KeyInner {
118 inner: ::std::cell::UnsafeCell { value: 0 as *mut _ },
119 }
120 };
121
122 #[cfg(any(windows,
123 target_os = "android",
124 target_os = "ios",
125 target_os = "openbsd",
126 target_arch = "aarch64"))]
127 const _INIT: __Key<$t> = __Key {
128 inner: ::std::thread::__scoped::KeyInner {
129 inner: ::std::thread::__scoped::OS_INIT,
130 marker: ::std::marker::PhantomData::<::std::cell::Cell<$t>>,
131 }
132 };
133
134 _INIT
135 })
136 }
137
138 #[macro_export]
139 #[allow_internal_unstable]
140 #[cfg(no_elf_tls)]
141 macro_rules! scoped_thread_local {
142 (static $name:ident: $t:ty) => (
143 static $name: ::std::thread::ScopedKey<$t> =
144 ::std::thread::ScopedKey::new();
145 );
146 (pub static $name:ident: $t:ty) => (
147 pub static $name: ::std::thread::ScopedKey<$t> =
148 ::std::thread::ScopedKey::new();
149 );
150 }
151
152 #[unstable(feature = "scoped_tls",
153 reason = "scoped TLS has yet to have wide enough use to fully consider \
154 stabilizing its interface")]
155 impl<T> ScopedKey<T> {
156 /// Inserts a value into this scoped thread local storage slot for a
157 /// duration of a closure.
158 ///
159 /// While `cb` is running, the value `t` will be returned by `get` unless
160 /// this function is called recursively inside of `cb`.
161 ///
162 /// Upon return, this function will restore the previous value, if any
163 /// was available.
164 ///
165 /// # Examples
166 ///
167 /// ```
168 /// # #![feature(scoped_tls)]
169 /// scoped_thread_local!(static FOO: u32);
170 ///
171 /// FOO.set(&100, || {
172 /// let val = FOO.with(|v| *v);
173 /// assert_eq!(val, 100);
174 ///
175 /// // set can be called recursively
176 /// FOO.set(&101, || {
177 /// // ...
178 /// });
179 ///
180 /// // Recursive calls restore the previous value.
181 /// let val = FOO.with(|v| *v);
182 /// assert_eq!(val, 100);
183 /// });
184 /// ```
185 pub fn set<R, F>(&'static self, t: &T, cb: F) -> R where
186 F: FnOnce() -> R,
187 {
188 struct Reset<'a, T: 'a> {
189 key: &'a __impl::KeyInner<T>,
190 val: *mut T,
191 }
192 impl<'a, T> Drop for Reset<'a, T> {
193 fn drop(&mut self) {
194 unsafe { self.key.set(self.val) }
195 }
196 }
197
198 let prev = unsafe {
199 let prev = self.inner.get();
200 self.inner.set(t as *const T as *mut T);
201 prev
202 };
203
204 let _reset = Reset { key: &self.inner, val: prev };
205 cb()
206 }
207
208 /// Gets a value out of this scoped variable.
209 ///
210 /// This function takes a closure which receives the value of this
211 /// variable.
212 ///
213 /// # Panics
214 ///
215 /// This function will panic if `set` has not previously been called.
216 ///
217 /// # Examples
218 ///
219 /// ```no_run
220 /// # #![feature(scoped_tls)]
221 /// scoped_thread_local!(static FOO: u32);
222 ///
223 /// FOO.with(|slot| {
224 /// // work with `slot`
225 /// });
226 /// ```
227 pub fn with<R, F>(&'static self, cb: F) -> R where
228 F: FnOnce(&T) -> R
229 {
230 unsafe {
231 let ptr = self.inner.get();
232 assert!(!ptr.is_null(), "cannot access a scoped thread local \
233 variable without calling `set` first");
234 cb(&*ptr)
235 }
236 }
237
238 /// Test whether this TLS key has been `set` for the current thread.
239 pub fn is_set(&'static self) -> bool {
240 unsafe { !self.inner.get().is_null() }
241 }
242 }
243
244 #[cfg(not(any(windows,
245 target_os = "android",
246 target_os = "ios",
247 target_os = "openbsd",
248 target_arch = "aarch64",
249 no_elf_tls)))]
250 mod imp {
251 use std::cell::UnsafeCell;
252
253 #[doc(hidden)]
254 pub struct KeyInner<T> { pub inner: UnsafeCell<*mut T> }
255
256 unsafe impl<T> ::marker::Sync for KeyInner<T> { }
257
258 #[doc(hidden)]
259 impl<T> KeyInner<T> {
260 #[doc(hidden)]
261 pub unsafe fn set(&self, ptr: *mut T) { *self.inner.get() = ptr; }
262 #[doc(hidden)]
263 pub unsafe fn get(&self) -> *mut T { *self.inner.get() }
264 }
265 }
266
267 #[cfg(any(windows,
268 target_os = "android",
269 target_os = "ios",
270 target_os = "openbsd",
271 target_arch = "aarch64",
272 no_elf_tls))]
273 mod imp {
274 use marker;
275 use std::cell::Cell;
276 use sys_common::thread_local::StaticKey as OsStaticKey;
277
278 #[doc(hidden)]
279 pub struct KeyInner<T> {
280 pub inner: OsStaticKey,
281 pub marker: marker::PhantomData<Cell<T>>,
282 }
283
284 unsafe impl<T> ::marker::Sync for KeyInner<T> { }
285
286 #[doc(hidden)]
287 impl<T> KeyInner<T> {
288 #[doc(hidden)]
289 pub unsafe fn set(&self, ptr: *mut T) { self.inner.set(ptr as *mut _) }
290 #[doc(hidden)]
291 pub unsafe fn get(&self) -> *mut T { self.inner.get() as *mut _ }
292 }
293 }
294
295
296 #[cfg(test)]
297 mod tests {
298 use cell::Cell;
299 use prelude::v1::*;
300
301 scoped_thread_local!(static FOO: u32);
302
303 #[test]
304 fn smoke() {
305 scoped_thread_local!(static BAR: u32);
306
307 assert!(!BAR.is_set());
308 BAR.set(&1, || {
309 assert!(BAR.is_set());
310 BAR.with(|slot| {
311 assert_eq!(*slot, 1);
312 });
313 });
314 assert!(!BAR.is_set());
315 }
316
317 #[test]
318 fn cell_allowed() {
319 scoped_thread_local!(static BAR: Cell<u32>);
320
321 BAR.set(&Cell::new(1), || {
322 BAR.with(|slot| {
323 assert_eq!(slot.get(), 1);
324 });
325 });
326 }
327
328 #[test]
329 fn scope_item_allowed() {
330 assert!(!FOO.is_set());
331 FOO.set(&1, || {
332 assert!(FOO.is_set());
333 FOO.with(|slot| {
334 assert_eq!(*slot, 1);
335 });
336 });
337 assert!(!FOO.is_set());
338 }
339 }