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