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