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