]>
Commit | Line | Data |
---|---|---|
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 | //! Thread local storage | |
c34b1796 | 12 | |
e9174d1e | 13 | #![unstable(feature = "thread_local_internals", issue = "0")] |
1a4d82fc JJ |
14 | |
15 | use cell::UnsafeCell; | |
32a655c1 | 16 | use fmt; |
9cc50fc6 | 17 | use mem; |
1a4d82fc JJ |
18 | |
19 | /// A thread local storage key which owns its contents. | |
20 | /// | |
21 | /// This key uses the fastest possible implementation available to it for the | |
7cac9316 XL |
22 | /// target platform. It is instantiated with the [`thread_local!`] macro and the |
23 | /// primary method is the [`with`] method. | |
1a4d82fc | 24 | /// |
7cac9316 | 25 | /// The [`with`] method yields a reference to the contained value which cannot be |
bd371182 | 26 | /// sent across threads or escape the given closure. |
1a4d82fc JJ |
27 | /// |
28 | /// # Initialization and Destruction | |
29 | /// | |
7cac9316 XL |
30 | /// Initialization is dynamically performed on the first call to [`with`] |
31 | /// within a thread, and values that implement [`Drop`] get destructed when a | |
8bb4bdeb | 32 | /// thread exits. Some caveats apply, which are explained below. |
1a4d82fc | 33 | /// |
ea8adc8c XL |
34 | /// A `LocalKey`'s initializer cannot recursively depend on itself, and using |
35 | /// a `LocalKey` in this way will cause the initializer to infinitely recurse | |
36 | /// on the first call to `with`. | |
37 | /// | |
c34b1796 | 38 | /// # Examples |
1a4d82fc JJ |
39 | /// |
40 | /// ``` | |
41 | /// use std::cell::RefCell; | |
85aaf69f | 42 | /// use std::thread; |
1a4d82fc | 43 | /// |
c34b1796 | 44 | /// thread_local!(static FOO: RefCell<u32> = RefCell::new(1)); |
1a4d82fc JJ |
45 | /// |
46 | /// FOO.with(|f| { | |
47 | /// assert_eq!(*f.borrow(), 1); | |
48 | /// *f.borrow_mut() = 2; | |
49 | /// }); | |
50 | /// | |
51 | /// // each thread starts out with the initial value of 1 | |
85aaf69f | 52 | /// thread::spawn(move|| { |
1a4d82fc JJ |
53 | /// FOO.with(|f| { |
54 | /// assert_eq!(*f.borrow(), 1); | |
55 | /// *f.borrow_mut() = 3; | |
56 | /// }); | |
57 | /// }); | |
58 | /// | |
59 | /// // we retain our original value of 2 despite the child thread | |
60 | /// FOO.with(|f| { | |
61 | /// assert_eq!(*f.borrow(), 2); | |
62 | /// }); | |
63 | /// ``` | |
7453a54e SL |
64 | /// |
65 | /// # Platform-specific behavior | |
66 | /// | |
67 | /// Note that a "best effort" is made to ensure that destructors for types | |
a7813a04 | 68 | /// stored in thread local storage are run, but not all platforms can guarantee |
7453a54e SL |
69 | /// that destructors will be run for all types in thread local storage. For |
70 | /// example, there are a number of known caveats where destructors are not run: | |
71 | /// | |
72 | /// 1. On Unix systems when pthread-based TLS is being used, destructors will | |
73 | /// not be run for TLS values on the main thread when it exits. Note that the | |
74 | /// application will exit immediately after the main thread exits as well. | |
75 | /// 2. On all platforms it's possible for TLS to re-initialize other TLS slots | |
76 | /// during destruction. Some platforms ensure that this cannot happen | |
77 | /// infinitely by preventing re-initialization of any slot that has been | |
78 | /// destroyed, but not all platforms have this guard. Those platforms that do | |
79 | /// not guard typically have a synthetic limit after which point no more | |
80 | /// destructors are run. | |
cc61c64b | 81 | /// 3. On macOS, initializing TLS during destruction of other TLS slots can |
7453a54e SL |
82 | /// sometimes cancel *all* destructors for the current thread, whether or not |
83 | /// the slots have already had their destructors run or not. | |
7cac9316 XL |
84 | /// |
85 | /// [`with`]: ../../std/thread/struct.LocalKey.html#method.with | |
86 | /// [`thread_local!`]: ../../std/macro.thread_local.html | |
87 | /// [`Drop`]: ../../std/ops/trait.Drop.html | |
85aaf69f | 88 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 SL |
89 | pub struct LocalKey<T: 'static> { |
90 | // This outer `LocalKey<T>` type is what's going to be stored in statics, | |
91 | // but actual data inside will sometimes be tagged with #[thread_local]. | |
92 | // It's not valid for a true static to reference a #[thread_local] static, | |
93 | // so we get around that by exposing an accessor through a layer of function | |
94 | // indirection (this thunk). | |
1a4d82fc | 95 | // |
9cc50fc6 SL |
96 | // Note that the thunk is itself unsafe because the returned lifetime of the |
97 | // slot where data lives, `'static`, is not actually valid. The lifetime | |
3b2f2976 | 98 | // here is actually slightly shorter than the currently running thread! |
9cc50fc6 SL |
99 | // |
100 | // Although this is an extra layer of indirection, it should in theory be | |
101 | // trivially devirtualizable by LLVM because the value of `inner` never | |
102 | // changes and the constant should be readonly within a crate. This mainly | |
103 | // only runs into problems when TLS statics are exported across crates. | |
3b2f2976 | 104 | inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>, |
1a4d82fc JJ |
105 | |
106 | // initialization routine to invoke to create a value | |
62682a34 | 107 | init: fn() -> T, |
1a4d82fc JJ |
108 | } |
109 | ||
8bb4bdeb | 110 | #[stable(feature = "std_debug", since = "1.16.0")] |
32a655c1 SL |
111 | impl<T: 'static> fmt::Debug for LocalKey<T> { |
112 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
113 | f.pad("LocalKey { .. }") | |
114 | } | |
115 | } | |
116 | ||
7cac9316 | 117 | /// Declare a new thread local storage key of type [`std::thread::LocalKey`]. |
62682a34 | 118 | /// |
3157f602 XL |
119 | /// # Syntax |
120 | /// | |
121 | /// The macro wraps any number of static declarations and makes them thread local. | |
041b39d2 | 122 | /// Publicity and attributes for each static are allowed. Example: |
3157f602 XL |
123 | /// |
124 | /// ``` | |
125 | /// use std::cell::RefCell; | |
126 | /// thread_local! { | |
127 | /// pub static FOO: RefCell<u32> = RefCell::new(1); | |
128 | /// | |
129 | /// #[allow(unused)] | |
130 | /// static BAR: RefCell<f32> = RefCell::new(1.0); | |
131 | /// } | |
132 | /// # fn main() {} | |
133 | /// ``` | |
134 | /// | |
7cac9316 | 135 | /// See [LocalKey documentation][`std::thread::LocalKey`] for more |
62682a34 | 136 | /// information. |
7cac9316 XL |
137 | /// |
138 | /// [`std::thread::LocalKey`]: ../std/thread/struct.LocalKey.html | |
1a4d82fc | 139 | #[macro_export] |
62682a34 | 140 | #[stable(feature = "rust1", since = "1.0.0")] |
c34b1796 | 141 | #[allow_internal_unstable] |
041b39d2 XL |
142 | macro_rules! thread_local { |
143 | // empty (base case for the recursion) | |
144 | () => {}; | |
145 | ||
146 | // process multiple declarations | |
147 | ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => ( | |
148 | __thread_local_inner!($(#[$attr])* $vis $name, $t, $init); | |
149 | thread_local!($($rest)*); | |
150 | ); | |
151 | ||
152 | // handle a single declaration | |
153 | ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => ( | |
154 | __thread_local_inner!($(#[$attr])* $vis $name, $t, $init); | |
155 | ); | |
156 | } | |
157 | ||
041b39d2 XL |
158 | #[doc(hidden)] |
159 | #[unstable(feature = "thread_local_internals", | |
160 | reason = "should not be necessary", | |
161 | issue = "0")] | |
162 | #[macro_export] | |
163 | #[allow_internal_unstable] | |
ea8adc8c | 164 | #[allow_internal_unsafe] |
041b39d2 | 165 | macro_rules! __thread_local_inner { |
ea8adc8c XL |
166 | (@key $(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => { |
167 | { | |
168 | #[inline] | |
041b39d2 XL |
169 | fn __init() -> $t { $init } |
170 | ||
3b2f2976 | 171 | unsafe fn __getit() -> $crate::option::Option< |
041b39d2 XL |
172 | &'static $crate::cell::UnsafeCell< |
173 | $crate::option::Option<$t>>> | |
174 | { | |
0bf4aa26 | 175 | #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))] |
83c7162d XL |
176 | static __KEY: $crate::thread::__StaticLocalKeyInner<$t> = |
177 | $crate::thread::__StaticLocalKeyInner::new(); | |
178 | ||
041b39d2 | 179 | #[thread_local] |
0bf4aa26 XL |
180 | #[cfg(all( |
181 | target_thread_local, | |
182 | not(all(target_arch = "wasm32", not(target_feature = "atomics"))), | |
183 | ))] | |
041b39d2 XL |
184 | static __KEY: $crate::thread::__FastLocalKeyInner<$t> = |
185 | $crate::thread::__FastLocalKeyInner::new(); | |
186 | ||
0bf4aa26 XL |
187 | #[cfg(all( |
188 | not(target_thread_local), | |
189 | not(all(target_arch = "wasm32", not(target_feature = "atomics"))), | |
190 | ))] | |
041b39d2 XL |
191 | static __KEY: $crate::thread::__OsLocalKeyInner<$t> = |
192 | $crate::thread::__OsLocalKeyInner::new(); | |
193 | ||
194 | __KEY.get() | |
195 | } | |
196 | ||
3b2f2976 XL |
197 | unsafe { |
198 | $crate::thread::LocalKey::new(__getit, __init) | |
199 | } | |
ea8adc8c XL |
200 | } |
201 | }; | |
202 | ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $init:expr) => { | |
ea8adc8c XL |
203 | $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> = |
204 | __thread_local_inner!(@key $(#[$attr])* $vis $name, $t, $init); | |
041b39d2 XL |
205 | } |
206 | } | |
207 | ||
041b39d2 | 208 | /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with). |
0531ce1d | 209 | #[stable(feature = "thread_local_try_with", since = "1.26.0")] |
041b39d2 XL |
210 | pub struct AccessError { |
211 | _private: (), | |
212 | } | |
213 | ||
0531ce1d | 214 | #[stable(feature = "thread_local_try_with", since = "1.26.0")] |
041b39d2 XL |
215 | impl fmt::Debug for AccessError { |
216 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
217 | f.debug_struct("AccessError").finish() | |
218 | } | |
219 | } | |
220 | ||
0531ce1d | 221 | #[stable(feature = "thread_local_try_with", since = "1.26.0")] |
041b39d2 XL |
222 | impl fmt::Display for AccessError { |
223 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
224 | fmt::Display::fmt("already destroyed", f) | |
225 | } | |
226 | } | |
227 | ||
c34b1796 | 228 | impl<T: 'static> LocalKey<T> { |
62682a34 SL |
229 | #[doc(hidden)] |
230 | #[unstable(feature = "thread_local_internals", | |
e9174d1e SL |
231 | reason = "recently added to create a key", |
232 | issue = "0")] | |
3b2f2976 XL |
233 | pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell<Option<T>>>, |
234 | init: fn() -> T) -> LocalKey<T> { | |
62682a34 | 235 | LocalKey { |
3b2f2976 XL |
236 | inner, |
237 | init, | |
62682a34 SL |
238 | } |
239 | } | |
240 | ||
9346a6ac | 241 | /// Acquires a reference to the value in this TLS key. |
1a4d82fc JJ |
242 | /// |
243 | /// This will lazily initialize the value if this thread has not referenced | |
244 | /// this key yet. | |
245 | /// | |
246 | /// # Panics | |
247 | /// | |
248 | /// This function will `panic!()` if the key currently has its | |
249 | /// destructor running, and it **may** panic if the destructor has | |
250 | /// previously been run for this thread. | |
85aaf69f | 251 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
252 | pub fn with<F, R>(&'static self, f: F) -> R |
253 | where F: FnOnce(&T) -> R { | |
041b39d2 XL |
254 | self.try_with(f).expect("cannot access a TLS value during or \ |
255 | after it is destroyed") | |
1a4d82fc JJ |
256 | } |
257 | ||
258 | unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T { | |
259 | // Execute the initialization up front, *then* move it into our slot, | |
260 | // just in case initialization fails. | |
261 | let value = (self.init)(); | |
262 | let ptr = slot.get(); | |
9cc50fc6 SL |
263 | |
264 | // note that this can in theory just be `*ptr = Some(value)`, but due to | |
265 | // the compiler will currently codegen that pattern with something like: | |
266 | // | |
267 | // ptr::drop_in_place(ptr) | |
268 | // ptr::write(ptr, Some(value)) | |
269 | // | |
270 | // Due to this pattern it's possible for the destructor of the value in | |
271 | // `ptr` (e.g. if this is being recursively initialized) to re-access | |
272 | // TLS, in which case there will be a `&` and `&mut` pointer to the same | |
273 | // value (an aliasing violation). To avoid setting the "I'm running a | |
274 | // destructor" flag we just use `mem::replace` which should sequence the | |
275 | // operations a little differently and make this safe to call. | |
276 | mem::replace(&mut *ptr, Some(value)); | |
277 | ||
1a4d82fc JJ |
278 | (*ptr).as_ref().unwrap() |
279 | } | |
280 | ||
041b39d2 XL |
281 | /// Acquires a reference to the value in this TLS key. |
282 | /// | |
283 | /// This will lazily initialize the value if this thread has not referenced | |
284 | /// this key yet. If the key has been destroyed (which may happen if this is called | |
8faf50e0 | 285 | /// in a destructor), this function will return an [`AccessError`](struct.AccessError.html). |
041b39d2 XL |
286 | /// |
287 | /// # Panics | |
288 | /// | |
289 | /// This function will still `panic!()` if the key is uninitialized and the | |
290 | /// key's initializer panics. | |
0531ce1d | 291 | #[stable(feature = "thread_local_try_with", since = "1.26.0")] |
041b39d2 | 292 | pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError> |
0531ce1d XL |
293 | where |
294 | F: FnOnce(&T) -> R, | |
295 | { | |
041b39d2 XL |
296 | unsafe { |
297 | let slot = (self.inner)().ok_or(AccessError { | |
298 | _private: (), | |
299 | })?; | |
300 | Ok(f(match *slot.get() { | |
301 | Some(ref inner) => inner, | |
302 | None => self.init(slot), | |
303 | })) | |
304 | } | |
305 | } | |
306 | } | |
307 | ||
83c7162d XL |
308 | /// On some platforms like wasm32 there's no threads, so no need to generate |
309 | /// thread locals and we can instead just use plain statics! | |
310 | #[doc(hidden)] | |
0bf4aa26 | 311 | #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))] |
83c7162d XL |
312 | pub mod statik { |
313 | use cell::UnsafeCell; | |
314 | use fmt; | |
315 | ||
316 | pub struct Key<T> { | |
317 | inner: UnsafeCell<Option<T>>, | |
318 | } | |
319 | ||
320 | unsafe impl<T> ::marker::Sync for Key<T> { } | |
321 | ||
322 | impl<T> fmt::Debug for Key<T> { | |
323 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
324 | f.pad("Key { .. }") | |
325 | } | |
326 | } | |
327 | ||
328 | impl<T> Key<T> { | |
329 | pub const fn new() -> Key<T> { | |
330 | Key { | |
331 | inner: UnsafeCell::new(None), | |
332 | } | |
333 | } | |
334 | ||
335 | pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> { | |
336 | Some(&*(&self.inner as *const _)) | |
337 | } | |
338 | } | |
339 | } | |
340 | ||
041b39d2 XL |
341 | #[doc(hidden)] |
342 | #[cfg(target_thread_local)] | |
343 | pub mod fast { | |
344 | use cell::{Cell, UnsafeCell}; | |
345 | use fmt; | |
346 | use mem; | |
347 | use ptr; | |
348 | use sys::fast_thread_local::{register_dtor, requires_move_before_drop}; | |
349 | ||
350 | pub struct Key<T> { | |
351 | inner: UnsafeCell<Option<T>>, | |
352 | ||
353 | // Metadata to keep track of the state of the destructor. Remember that | |
354 | // these variables are thread-local, not global. | |
355 | dtor_registered: Cell<bool>, | |
356 | dtor_running: Cell<bool>, | |
357 | } | |
358 | ||
359 | impl<T> fmt::Debug for Key<T> { | |
360 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
361 | f.pad("Key { .. }") | |
362 | } | |
363 | } | |
364 | ||
041b39d2 XL |
365 | impl<T> Key<T> { |
366 | pub const fn new() -> Key<T> { | |
367 | Key { | |
368 | inner: UnsafeCell::new(None), | |
369 | dtor_registered: Cell::new(false), | |
370 | dtor_running: Cell::new(false) | |
371 | } | |
372 | } | |
373 | ||
3b2f2976 XL |
374 | pub unsafe fn get(&self) -> Option<&'static UnsafeCell<Option<T>>> { |
375 | if mem::needs_drop::<T>() && self.dtor_running.get() { | |
376 | return None | |
041b39d2 | 377 | } |
3b2f2976 XL |
378 | self.register_dtor(); |
379 | Some(&*(&self.inner as *const _)) | |
041b39d2 XL |
380 | } |
381 | ||
382 | unsafe fn register_dtor(&self) { | |
383 | if !mem::needs_drop::<T>() || self.dtor_registered.get() { | |
384 | return | |
385 | } | |
386 | ||
387 | register_dtor(self as *const _ as *mut u8, | |
388 | destroy_value::<T>); | |
389 | self.dtor_registered.set(true); | |
390 | } | |
391 | } | |
392 | ||
393 | unsafe extern fn destroy_value<T>(ptr: *mut u8) { | |
394 | let ptr = ptr as *mut Key<T>; | |
395 | // Right before we run the user destructor be sure to flag the | |
396 | // destructor as running for this thread so calls to `get` will return | |
397 | // `None`. | |
398 | (*ptr).dtor_running.set(true); | |
399 | ||
400 | // Some implementations may require us to move the value before we drop | |
401 | // it as it could get re-initialized in-place during destruction. | |
402 | // | |
403 | // Hence, we use `ptr::read` on those platforms (to move to a "safe" | |
404 | // location) instead of drop_in_place. | |
405 | if requires_move_before_drop() { | |
406 | ptr::read((*ptr).inner.get()); | |
407 | } else { | |
408 | ptr::drop_in_place((*ptr).inner.get()); | |
409 | } | |
410 | } | |
1a4d82fc JJ |
411 | } |
412 | ||
d9579d0f | 413 | #[doc(hidden)] |
9cc50fc6 | 414 | pub mod os { |
62682a34 | 415 | use cell::{Cell, UnsafeCell}; |
32a655c1 | 416 | use fmt; |
62682a34 | 417 | use marker; |
85aaf69f | 418 | use ptr; |
1a4d82fc JJ |
419 | use sys_common::thread_local::StaticKey as OsStaticKey; |
420 | ||
1a4d82fc | 421 | pub struct Key<T> { |
1a4d82fc | 422 | // OS-TLS key that we'll use to key off. |
62682a34 SL |
423 | os: OsStaticKey, |
424 | marker: marker::PhantomData<Cell<T>>, | |
1a4d82fc JJ |
425 | } |
426 | ||
32a655c1 SL |
427 | impl<T> fmt::Debug for Key<T> { |
428 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
429 | f.pad("Key { .. }") | |
430 | } | |
431 | } | |
432 | ||
1a4d82fc JJ |
433 | unsafe impl<T> ::marker::Sync for Key<T> { } |
434 | ||
435 | struct Value<T: 'static> { | |
436 | key: &'static Key<T>, | |
62682a34 | 437 | value: UnsafeCell<Option<T>>, |
1a4d82fc JJ |
438 | } |
439 | ||
62682a34 SL |
440 | impl<T: 'static> Key<T> { |
441 | pub const fn new() -> Key<T> { | |
442 | Key { | |
443 | os: OsStaticKey::new(Some(destroy_value::<T>)), | |
444 | marker: marker::PhantomData | |
445 | } | |
1a4d82fc JJ |
446 | } |
447 | ||
3b2f2976 XL |
448 | pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell<Option<T>>> { |
449 | let ptr = self.os.get() as *mut Value<T>; | |
450 | if !ptr.is_null() { | |
451 | if ptr as usize == 1 { | |
452 | return None | |
1a4d82fc | 453 | } |
3b2f2976 | 454 | return Some(&(*ptr).value); |
7453a54e | 455 | } |
3b2f2976 XL |
456 | |
457 | // If the lookup returned null, we haven't initialized our own | |
458 | // local copy, so do that now. | |
459 | let ptr: Box<Value<T>> = box Value { | |
460 | key: self, | |
461 | value: UnsafeCell::new(None), | |
462 | }; | |
463 | let ptr = Box::into_raw(ptr); | |
464 | self.os.set(ptr as *mut u8); | |
465 | Some(&(*ptr).value) | |
1a4d82fc JJ |
466 | } |
467 | } | |
468 | ||
041b39d2 | 469 | unsafe extern fn destroy_value<T: 'static>(ptr: *mut u8) { |
1a4d82fc JJ |
470 | // The OS TLS ensures that this key contains a NULL value when this |
471 | // destructor starts to run. We set it back to a sentinel value of 1 to | |
472 | // ensure that any future calls to `get` for this thread will return | |
473 | // `None`. | |
474 | // | |
475 | // Note that to prevent an infinite loop we reset it back to null right | |
476 | // before we return from the destructor ourselves. | |
d9579d0f | 477 | let ptr = Box::from_raw(ptr as *mut Value<T>); |
1a4d82fc JJ |
478 | let key = ptr.key; |
479 | key.os.set(1 as *mut u8); | |
480 | drop(ptr); | |
85aaf69f | 481 | key.os.set(ptr::null_mut()); |
1a4d82fc JJ |
482 | } |
483 | } | |
484 | ||
c30ab7b3 | 485 | #[cfg(all(test, not(target_os = "emscripten")))] |
1a4d82fc | 486 | mod tests { |
1a4d82fc | 487 | use sync::mpsc::{channel, Sender}; |
62682a34 | 488 | use cell::{Cell, UnsafeCell}; |
85aaf69f | 489 | use thread; |
1a4d82fc JJ |
490 | |
491 | struct Foo(Sender<()>); | |
492 | ||
493 | impl Drop for Foo { | |
494 | fn drop(&mut self) { | |
495 | let Foo(ref s) = *self; | |
496 | s.send(()).unwrap(); | |
497 | } | |
498 | } | |
499 | ||
500 | #[test] | |
501 | fn smoke_no_dtor() { | |
62682a34 | 502 | thread_local!(static FOO: Cell<i32> = Cell::new(1)); |
1a4d82fc | 503 | |
62682a34 SL |
504 | FOO.with(|f| { |
505 | assert_eq!(f.get(), 1); | |
506 | f.set(2); | |
1a4d82fc JJ |
507 | }); |
508 | let (tx, rx) = channel(); | |
85aaf69f | 509 | let _t = thread::spawn(move|| { |
62682a34 SL |
510 | FOO.with(|f| { |
511 | assert_eq!(f.get(), 1); | |
1a4d82fc JJ |
512 | }); |
513 | tx.send(()).unwrap(); | |
514 | }); | |
515 | rx.recv().unwrap(); | |
516 | ||
62682a34 SL |
517 | FOO.with(|f| { |
518 | assert_eq!(f.get(), 2); | |
1a4d82fc JJ |
519 | }); |
520 | } | |
521 | ||
522 | #[test] | |
523 | fn states() { | |
524 | struct Foo; | |
525 | impl Drop for Foo { | |
526 | fn drop(&mut self) { | |
0531ce1d | 527 | assert!(FOO.try_with(|_| ()).is_err()); |
1a4d82fc JJ |
528 | } |
529 | } | |
0531ce1d | 530 | thread_local!(static FOO: Foo = Foo); |
1a4d82fc | 531 | |
85aaf69f | 532 | thread::spawn(|| { |
0531ce1d | 533 | assert!(FOO.try_with(|_| ()).is_ok()); |
1a4d82fc JJ |
534 | }).join().ok().unwrap(); |
535 | } | |
536 | ||
537 | #[test] | |
538 | fn smoke_dtor() { | |
62682a34 | 539 | thread_local!(static FOO: UnsafeCell<Option<Foo>> = UnsafeCell::new(None)); |
1a4d82fc JJ |
540 | |
541 | let (tx, rx) = channel(); | |
85aaf69f | 542 | let _t = thread::spawn(move|| unsafe { |
1a4d82fc JJ |
543 | let mut tx = Some(tx); |
544 | FOO.with(|f| { | |
545 | *f.get() = Some(Foo(tx.take().unwrap())); | |
546 | }); | |
547 | }); | |
548 | rx.recv().unwrap(); | |
549 | } | |
550 | ||
551 | #[test] | |
552 | fn circular() { | |
553 | struct S1; | |
554 | struct S2; | |
62682a34 SL |
555 | thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None)); |
556 | thread_local!(static K2: UnsafeCell<Option<S2>> = UnsafeCell::new(None)); | |
c34b1796 | 557 | static mut HITS: u32 = 0; |
1a4d82fc JJ |
558 | |
559 | impl Drop for S1 { | |
560 | fn drop(&mut self) { | |
561 | unsafe { | |
562 | HITS += 1; | |
0531ce1d | 563 | if K2.try_with(|_| ()).is_err() { |
1a4d82fc JJ |
564 | assert_eq!(HITS, 3); |
565 | } else { | |
566 | if HITS == 1 { | |
567 | K2.with(|s| *s.get() = Some(S2)); | |
568 | } else { | |
569 | assert_eq!(HITS, 3); | |
570 | } | |
571 | } | |
572 | } | |
573 | } | |
574 | } | |
575 | impl Drop for S2 { | |
576 | fn drop(&mut self) { | |
577 | unsafe { | |
578 | HITS += 1; | |
0531ce1d | 579 | assert!(K1.try_with(|_| ()).is_ok()); |
1a4d82fc JJ |
580 | assert_eq!(HITS, 2); |
581 | K1.with(|s| *s.get() = Some(S1)); | |
582 | } | |
583 | } | |
584 | } | |
585 | ||
85aaf69f | 586 | thread::spawn(move|| { |
1a4d82fc JJ |
587 | drop(S1); |
588 | }).join().ok().unwrap(); | |
589 | } | |
590 | ||
591 | #[test] | |
592 | fn self_referential() { | |
593 | struct S1; | |
62682a34 | 594 | thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None)); |
1a4d82fc JJ |
595 | |
596 | impl Drop for S1 { | |
597 | fn drop(&mut self) { | |
0531ce1d | 598 | assert!(K1.try_with(|_| ()).is_err()); |
1a4d82fc JJ |
599 | } |
600 | } | |
601 | ||
85aaf69f | 602 | thread::spawn(move|| unsafe { |
1a4d82fc JJ |
603 | K1.with(|s| *s.get() = Some(S1)); |
604 | }).join().ok().unwrap(); | |
605 | } | |
606 | ||
7453a54e | 607 | // Note that this test will deadlock if TLS destructors aren't run (this |
cc61c64b | 608 | // requires the destructor to be run to pass the test). macOS has a known bug |
7453a54e | 609 | // where dtors-in-dtors may cancel other destructors, so we just ignore this |
cc61c64b | 610 | // test on macOS. |
1a4d82fc | 611 | #[test] |
7453a54e | 612 | #[cfg_attr(target_os = "macos", ignore)] |
1a4d82fc JJ |
613 | fn dtors_in_dtors_in_dtors() { |
614 | struct S1(Sender<()>); | |
62682a34 SL |
615 | thread_local!(static K1: UnsafeCell<Option<S1>> = UnsafeCell::new(None)); |
616 | thread_local!(static K2: UnsafeCell<Option<Foo>> = UnsafeCell::new(None)); | |
1a4d82fc JJ |
617 | |
618 | impl Drop for S1 { | |
619 | fn drop(&mut self) { | |
620 | let S1(ref tx) = *self; | |
621 | unsafe { | |
0531ce1d | 622 | let _ = K2.try_with(|s| *s.get() = Some(Foo(tx.clone()))); |
1a4d82fc JJ |
623 | } |
624 | } | |
625 | } | |
626 | ||
627 | let (tx, rx) = channel(); | |
85aaf69f | 628 | let _t = thread::spawn(move|| unsafe { |
1a4d82fc JJ |
629 | let mut tx = Some(tx); |
630 | K1.with(|s| *s.get() = Some(S1(tx.take().unwrap()))); | |
631 | }); | |
632 | rx.recv().unwrap(); | |
633 | } | |
634 | } | |
635 | ||
636 | #[cfg(test)] | |
637 | mod dynamic_tests { | |
1a4d82fc JJ |
638 | use cell::RefCell; |
639 | use collections::HashMap; | |
640 | ||
641 | #[test] | |
642 | fn smoke() { | |
c34b1796 AL |
643 | fn square(i: i32) -> i32 { i * i } |
644 | thread_local!(static FOO: i32 = square(3)); | |
1a4d82fc JJ |
645 | |
646 | FOO.with(|f| { | |
647 | assert_eq!(*f, 9); | |
648 | }); | |
649 | } | |
650 | ||
651 | #[test] | |
652 | fn hashmap() { | |
c34b1796 | 653 | fn map() -> RefCell<HashMap<i32, i32>> { |
1a4d82fc JJ |
654 | let mut m = HashMap::new(); |
655 | m.insert(1, 2); | |
656 | RefCell::new(m) | |
657 | } | |
c34b1796 | 658 | thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map()); |
1a4d82fc JJ |
659 | |
660 | FOO.with(|map| { | |
c34b1796 | 661 | assert_eq!(map.borrow()[&1], 2); |
1a4d82fc JJ |
662 | }); |
663 | } | |
664 | ||
665 | #[test] | |
666 | fn refcell_vec() { | |
c34b1796 | 667 | thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3])); |
1a4d82fc JJ |
668 | |
669 | FOO.with(|vec| { | |
670 | assert_eq!(vec.borrow().len(), 3); | |
671 | vec.borrow_mut().push(4); | |
672 | assert_eq!(vec.borrow()[3], 4); | |
673 | }); | |
674 | } | |
675 | } |