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