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