]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/mutex.rs
Auto merge of #74489 - jyn514:assoc-items, r=manishearth,petrochenkov
[rust.git] / library / std / src / sync / mutex.rs
1 use crate::cell::UnsafeCell;
2 use crate::fmt;
3 use crate::mem;
4 use crate::ops::{Deref, DerefMut};
5 use crate::ptr;
6 use crate::sys_common::mutex as sys;
7 use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
8
9 /// A mutual exclusion primitive useful for protecting shared data
10 ///
11 /// This mutex will block threads waiting for the lock to become available. The
12 /// mutex can also be statically initialized or created via a [`new`]
13 /// constructor. Each mutex has a type parameter which represents the data that
14 /// it is protecting. The data can only be accessed through the RAII guards
15 /// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
16 /// ever accessed when the mutex is locked.
17 ///
18 /// # Poisoning
19 ///
20 /// The mutexes in this module implement a strategy called "poisoning" where a
21 /// mutex is considered poisoned whenever a thread panics while holding the
22 /// mutex. Once a mutex is poisoned, all other threads are unable to access the
23 /// data by default as it is likely tainted (some invariant is not being
24 /// upheld).
25 ///
26 /// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
27 /// [`Result`] which indicates whether a mutex has been poisoned or not. Most
28 /// usage of a mutex will simply [`unwrap()`] these results, propagating panics
29 /// among threads to ensure that a possibly invalid invariant is not witnessed.
30 ///
31 /// A poisoned mutex, however, does not prevent all access to the underlying
32 /// data. The [`PoisonError`] type has an [`into_inner`] method which will return
33 /// the guard that would have otherwise been returned on a successful lock. This
34 /// allows access to the data, despite the lock being poisoned.
35 ///
36 /// [`new`]: Self::new
37 /// [`lock`]: Self::lock
38 /// [`try_lock`]: Self::try_lock
39 /// [`unwrap()`]: Result::unwrap
40 /// [`PoisonError`]: super::PoisonError
41 /// [`into_inner`]: super::PoisonError::into_inner
42 ///
43 /// # Examples
44 ///
45 /// ```
46 /// use std::sync::{Arc, Mutex};
47 /// use std::thread;
48 /// use std::sync::mpsc::channel;
49 ///
50 /// const N: usize = 10;
51 ///
52 /// // Spawn a few threads to increment a shared variable (non-atomically), and
53 /// // let the main thread know once all increments are done.
54 /// //
55 /// // Here we're using an Arc to share memory among threads, and the data inside
56 /// // the Arc is protected with a mutex.
57 /// let data = Arc::new(Mutex::new(0));
58 ///
59 /// let (tx, rx) = channel();
60 /// for _ in 0..N {
61 ///     let (data, tx) = (Arc::clone(&data), tx.clone());
62 ///     thread::spawn(move || {
63 ///         // The shared state can only be accessed once the lock is held.
64 ///         // Our non-atomic increment is safe because we're the only thread
65 ///         // which can access the shared state when the lock is held.
66 ///         //
67 ///         // We unwrap() the return value to assert that we are not expecting
68 ///         // threads to ever fail while holding the lock.
69 ///         let mut data = data.lock().unwrap();
70 ///         *data += 1;
71 ///         if *data == N {
72 ///             tx.send(()).unwrap();
73 ///         }
74 ///         // the lock is unlocked here when `data` goes out of scope.
75 ///     });
76 /// }
77 ///
78 /// rx.recv().unwrap();
79 /// ```
80 ///
81 /// To recover from a poisoned mutex:
82 ///
83 /// ```
84 /// use std::sync::{Arc, Mutex};
85 /// use std::thread;
86 ///
87 /// let lock = Arc::new(Mutex::new(0_u32));
88 /// let lock2 = lock.clone();
89 ///
90 /// let _ = thread::spawn(move || -> () {
91 ///     // This thread will acquire the mutex first, unwrapping the result of
92 ///     // `lock` because the lock has not been poisoned.
93 ///     let _guard = lock2.lock().unwrap();
94 ///
95 ///     // This panic while holding the lock (`_guard` is in scope) will poison
96 ///     // the mutex.
97 ///     panic!();
98 /// }).join();
99 ///
100 /// // The lock is poisoned by this point, but the returned result can be
101 /// // pattern matched on to return the underlying guard on both branches.
102 /// let mut guard = match lock.lock() {
103 ///     Ok(guard) => guard,
104 ///     Err(poisoned) => poisoned.into_inner(),
105 /// };
106 ///
107 /// *guard += 1;
108 /// ```
109 ///
110 /// It is sometimes necessary to manually drop the mutex guard to unlock it
111 /// sooner than the end of the enclosing scope.
112 ///
113 /// ```
114 /// use std::sync::{Arc, Mutex};
115 /// use std::thread;
116 ///
117 /// const N: usize = 3;
118 ///
119 /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
120 /// let res_mutex = Arc::new(Mutex::new(0));
121 ///
122 /// let mut threads = Vec::with_capacity(N);
123 /// (0..N).for_each(|_| {
124 ///     let data_mutex_clone = Arc::clone(&data_mutex);
125 ///     let res_mutex_clone = Arc::clone(&res_mutex);
126 ///
127 ///     threads.push(thread::spawn(move || {
128 ///         let mut data = data_mutex_clone.lock().unwrap();
129 ///         // This is the result of some important and long-ish work.
130 ///         let result = data.iter().fold(0, |acc, x| acc + x * 2);
131 ///         data.push(result);
132 ///         drop(data);
133 ///         *res_mutex_clone.lock().unwrap() += result;
134 ///     }));
135 /// });
136 ///
137 /// let mut data = data_mutex.lock().unwrap();
138 /// // This is the result of some important and long-ish work.
139 /// let result = data.iter().fold(0, |acc, x| acc + x * 2);
140 /// data.push(result);
141 /// // We drop the `data` explicitly because it's not necessary anymore and the
142 /// // thread still has work to do. This allow other threads to start working on
143 /// // the data immediately, without waiting for the rest of the unrelated work
144 /// // to be done here.
145 /// //
146 /// // It's even more important here than in the threads because we `.join` the
147 /// // threads after that. If we had not dropped the mutex guard, a thread could
148 /// // be waiting forever for it, causing a deadlock.
149 /// drop(data);
150 /// // Here the mutex guard is not assigned to a variable and so, even if the
151 /// // scope does not end after this line, the mutex is still released: there is
152 /// // no deadlock.
153 /// *res_mutex.lock().unwrap() += result;
154 ///
155 /// threads.into_iter().for_each(|thread| {
156 ///     thread
157 ///         .join()
158 ///         .expect("The thread creating or execution failed !")
159 /// });
160 ///
161 /// assert_eq!(*res_mutex.lock().unwrap(), 800);
162 /// ```
163 #[stable(feature = "rust1", since = "1.0.0")]
164 #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")]
165 pub struct Mutex<T: ?Sized> {
166     // Note that this mutex is in a *box*, not inlined into the struct itself.
167     // Once a native mutex has been used once, its address can never change (it
168     // can't be moved). This mutex type can be safely moved at any time, so to
169     // ensure that the native mutex is used correctly we box the inner mutex to
170     // give it a constant address.
171     inner: Box<sys::Mutex>,
172     poison: poison::Flag,
173     data: UnsafeCell<T>,
174 }
175
176 // these are the only places where `T: Send` matters; all other
177 // functionality works fine on a single thread.
178 #[stable(feature = "rust1", since = "1.0.0")]
179 unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
180 #[stable(feature = "rust1", since = "1.0.0")]
181 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
182
183 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
184 /// dropped (falls out of scope), the lock will be unlocked.
185 ///
186 /// The data protected by the mutex can be accessed through this guard via its
187 /// [`Deref`] and [`DerefMut`] implementations.
188 ///
189 /// This structure is created by the [`lock`] and [`try_lock`] methods on
190 /// [`Mutex`].
191 ///
192 /// [`lock`]: Mutex::lock
193 /// [`try_lock`]: Mutex::try_lock
194 #[must_use = "if unused the Mutex will immediately unlock"]
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub struct MutexGuard<'a, T: ?Sized + 'a> {
197     lock: &'a Mutex<T>,
198     poison: poison::Guard,
199 }
200
201 #[stable(feature = "rust1", since = "1.0.0")]
202 impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
203 #[stable(feature = "mutexguard", since = "1.19.0")]
204 unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
205
206 impl<T> Mutex<T> {
207     /// Creates a new mutex in an unlocked state ready for use.
208     ///
209     /// # Examples
210     ///
211     /// ```
212     /// use std::sync::Mutex;
213     ///
214     /// let mutex = Mutex::new(0);
215     /// ```
216     #[stable(feature = "rust1", since = "1.0.0")]
217     pub fn new(t: T) -> Mutex<T> {
218         let mut m = Mutex {
219             inner: box sys::Mutex::new(),
220             poison: poison::Flag::new(),
221             data: UnsafeCell::new(t),
222         };
223         unsafe {
224             m.inner.init();
225         }
226         m
227     }
228 }
229
230 impl<T: ?Sized> Mutex<T> {
231     /// Acquires a mutex, blocking the current thread until it is able to do so.
232     ///
233     /// This function will block the local thread until it is available to acquire
234     /// the mutex. Upon returning, the thread is the only thread with the lock
235     /// held. An RAII guard is returned to allow scoped unlock of the lock. When
236     /// the guard goes out of scope, the mutex will be unlocked.
237     ///
238     /// The exact behavior on locking a mutex in the thread which already holds
239     /// the lock is left unspecified. However, this function will not return on
240     /// the second call (it might panic or deadlock, for example).
241     ///
242     /// # Errors
243     ///
244     /// If another user of this mutex panicked while holding the mutex, then
245     /// this call will return an error once the mutex is acquired.
246     ///
247     /// # Panics
248     ///
249     /// This function might panic when called if the lock is already held by
250     /// the current thread.
251     ///
252     /// # Examples
253     ///
254     /// ```
255     /// use std::sync::{Arc, Mutex};
256     /// use std::thread;
257     ///
258     /// let mutex = Arc::new(Mutex::new(0));
259     /// let c_mutex = mutex.clone();
260     ///
261     /// thread::spawn(move || {
262     ///     *c_mutex.lock().unwrap() = 10;
263     /// }).join().expect("thread::spawn failed");
264     /// assert_eq!(*mutex.lock().unwrap(), 10);
265     /// ```
266     #[stable(feature = "rust1", since = "1.0.0")]
267     pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
268         unsafe {
269             self.inner.raw_lock();
270             MutexGuard::new(self)
271         }
272     }
273
274     /// Attempts to acquire this lock.
275     ///
276     /// If the lock could not be acquired at this time, then [`Err`] is returned.
277     /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
278     /// guard is dropped.
279     ///
280     /// This function does not block.
281     ///
282     /// # Errors
283     ///
284     /// If another user of this mutex panicked while holding the mutex, then
285     /// this call will return failure if the mutex would otherwise be
286     /// acquired.
287     ///
288     /// # Examples
289     ///
290     /// ```
291     /// use std::sync::{Arc, Mutex};
292     /// use std::thread;
293     ///
294     /// let mutex = Arc::new(Mutex::new(0));
295     /// let c_mutex = mutex.clone();
296     ///
297     /// thread::spawn(move || {
298     ///     let mut lock = c_mutex.try_lock();
299     ///     if let Ok(ref mut mutex) = lock {
300     ///         **mutex = 10;
301     ///     } else {
302     ///         println!("try_lock failed");
303     ///     }
304     /// }).join().expect("thread::spawn failed");
305     /// assert_eq!(*mutex.lock().unwrap(), 10);
306     /// ```
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
309         unsafe {
310             if self.inner.try_lock() {
311                 Ok(MutexGuard::new(self)?)
312             } else {
313                 Err(TryLockError::WouldBlock)
314             }
315         }
316     }
317
318     /// Determines whether the mutex is poisoned.
319     ///
320     /// If another thread is active, the mutex can still become poisoned at any
321     /// time. You should not trust a `false` value for program correctness
322     /// without additional synchronization.
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use std::sync::{Arc, Mutex};
328     /// use std::thread;
329     ///
330     /// let mutex = Arc::new(Mutex::new(0));
331     /// let c_mutex = mutex.clone();
332     ///
333     /// let _ = thread::spawn(move || {
334     ///     let _lock = c_mutex.lock().unwrap();
335     ///     panic!(); // the mutex gets poisoned
336     /// }).join();
337     /// assert_eq!(mutex.is_poisoned(), true);
338     /// ```
339     #[inline]
340     #[stable(feature = "sync_poison", since = "1.2.0")]
341     pub fn is_poisoned(&self) -> bool {
342         self.poison.get()
343     }
344
345     /// Consumes this mutex, returning the underlying data.
346     ///
347     /// # Errors
348     ///
349     /// If another user of this mutex panicked while holding the mutex, then
350     /// this call will return an error instead.
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// use std::sync::Mutex;
356     ///
357     /// let mutex = Mutex::new(0);
358     /// assert_eq!(mutex.into_inner().unwrap(), 0);
359     /// ```
360     #[stable(feature = "mutex_into_inner", since = "1.6.0")]
361     pub fn into_inner(self) -> LockResult<T>
362     where
363         T: Sized,
364     {
365         // We know statically that there are no outstanding references to
366         // `self` so there's no need to lock the inner mutex.
367         //
368         // To get the inner value, we'd like to call `data.into_inner()`,
369         // but because `Mutex` impl-s `Drop`, we can't move out of it, so
370         // we'll have to destructure it manually instead.
371         unsafe {
372             // Like `let Mutex { inner, poison, data } = self`.
373             let (inner, poison, data) = {
374                 let Mutex { ref inner, ref poison, ref data } = self;
375                 (ptr::read(inner), ptr::read(poison), ptr::read(data))
376             };
377             mem::forget(self);
378             inner.destroy(); // Keep in sync with the `Drop` impl.
379             drop(inner);
380
381             poison::map_result(poison.borrow(), |_| data.into_inner())
382         }
383     }
384
385     /// Returns a mutable reference to the underlying data.
386     ///
387     /// Since this call borrows the `Mutex` mutably, no actual locking needs to
388     /// take place -- the mutable borrow statically guarantees no locks exist.
389     ///
390     /// # Errors
391     ///
392     /// If another user of this mutex panicked while holding the mutex, then
393     /// this call will return an error instead.
394     ///
395     /// # Examples
396     ///
397     /// ```
398     /// use std::sync::Mutex;
399     ///
400     /// let mut mutex = Mutex::new(0);
401     /// *mutex.get_mut().unwrap() = 10;
402     /// assert_eq!(*mutex.lock().unwrap(), 10);
403     /// ```
404     #[stable(feature = "mutex_get_mut", since = "1.6.0")]
405     pub fn get_mut(&mut self) -> LockResult<&mut T> {
406         // We know statically that there are no other references to `self`, so
407         // there's no need to lock the inner mutex.
408         let data = unsafe { &mut *self.data.get() };
409         poison::map_result(self.poison.borrow(), |_| data)
410     }
411 }
412
413 #[stable(feature = "rust1", since = "1.0.0")]
414 unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
415     fn drop(&mut self) {
416         // This is actually safe b/c we know that there is no further usage of
417         // this mutex (it's up to the user to arrange for a mutex to get
418         // dropped, that's not our job)
419         //
420         // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
421         unsafe { self.inner.destroy() }
422     }
423 }
424
425 #[stable(feature = "mutex_from", since = "1.24.0")]
426 impl<T> From<T> for Mutex<T> {
427     /// Creates a new mutex in an unlocked state ready for use.
428     /// This is equivalent to [`Mutex::new`].
429     fn from(t: T) -> Self {
430         Mutex::new(t)
431     }
432 }
433
434 #[stable(feature = "mutex_default", since = "1.10.0")]
435 impl<T: ?Sized + Default> Default for Mutex<T> {
436     /// Creates a `Mutex<T>`, with the `Default` value for T.
437     fn default() -> Mutex<T> {
438         Mutex::new(Default::default())
439     }
440 }
441
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
444     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445         match self.try_lock() {
446             Ok(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(),
447             Err(TryLockError::Poisoned(err)) => {
448                 f.debug_struct("Mutex").field("data", &&**err.get_ref()).finish()
449             }
450             Err(TryLockError::WouldBlock) => {
451                 struct LockedPlaceholder;
452                 impl fmt::Debug for LockedPlaceholder {
453                     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454                         f.write_str("<locked>")
455                     }
456                 }
457
458                 f.debug_struct("Mutex").field("data", &LockedPlaceholder).finish()
459             }
460         }
461     }
462 }
463
464 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
465     unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
466         poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
467     }
468 }
469
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
472     type Target = T;
473
474     fn deref(&self) -> &T {
475         unsafe { &*self.lock.data.get() }
476     }
477 }
478
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
481     fn deref_mut(&mut self) -> &mut T {
482         unsafe { &mut *self.lock.data.get() }
483     }
484 }
485
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
488     #[inline]
489     fn drop(&mut self) {
490         unsafe {
491             self.lock.poison.done(&self.poison);
492             self.lock.inner.raw_unlock();
493         }
494     }
495 }
496
497 #[stable(feature = "std_debug", since = "1.16.0")]
498 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
499     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500         fmt::Debug::fmt(&**self, f)
501     }
502 }
503
504 #[stable(feature = "std_guard_impls", since = "1.20.0")]
505 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
506     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507         (**self).fmt(f)
508     }
509 }
510
511 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
512     &guard.lock.inner
513 }
514
515 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
516     &guard.lock.poison
517 }
518
519 #[cfg(all(test, not(target_os = "emscripten")))]
520 mod tests {
521     use crate::sync::atomic::{AtomicUsize, Ordering};
522     use crate::sync::mpsc::channel;
523     use crate::sync::{Arc, Condvar, Mutex};
524     use crate::thread;
525
526     struct Packet<T>(Arc<(Mutex<T>, Condvar)>);
527
528     #[derive(Eq, PartialEq, Debug)]
529     struct NonCopy(i32);
530
531     #[test]
532     fn smoke() {
533         let m = Mutex::new(());
534         drop(m.lock().unwrap());
535         drop(m.lock().unwrap());
536     }
537
538     #[test]
539     fn lots_and_lots() {
540         const J: u32 = 1000;
541         const K: u32 = 3;
542
543         let m = Arc::new(Mutex::new(0));
544
545         fn inc(m: &Mutex<u32>) {
546             for _ in 0..J {
547                 *m.lock().unwrap() += 1;
548             }
549         }
550
551         let (tx, rx) = channel();
552         for _ in 0..K {
553             let tx2 = tx.clone();
554             let m2 = m.clone();
555             thread::spawn(move || {
556                 inc(&m2);
557                 tx2.send(()).unwrap();
558             });
559             let tx2 = tx.clone();
560             let m2 = m.clone();
561             thread::spawn(move || {
562                 inc(&m2);
563                 tx2.send(()).unwrap();
564             });
565         }
566
567         drop(tx);
568         for _ in 0..2 * K {
569             rx.recv().unwrap();
570         }
571         assert_eq!(*m.lock().unwrap(), J * K * 2);
572     }
573
574     #[test]
575     fn try_lock() {
576         let m = Mutex::new(());
577         *m.try_lock().unwrap() = ();
578     }
579
580     #[test]
581     fn test_into_inner() {
582         let m = Mutex::new(NonCopy(10));
583         assert_eq!(m.into_inner().unwrap(), NonCopy(10));
584     }
585
586     #[test]
587     fn test_into_inner_drop() {
588         struct Foo(Arc<AtomicUsize>);
589         impl Drop for Foo {
590             fn drop(&mut self) {
591                 self.0.fetch_add(1, Ordering::SeqCst);
592             }
593         }
594         let num_drops = Arc::new(AtomicUsize::new(0));
595         let m = Mutex::new(Foo(num_drops.clone()));
596         assert_eq!(num_drops.load(Ordering::SeqCst), 0);
597         {
598             let _inner = m.into_inner().unwrap();
599             assert_eq!(num_drops.load(Ordering::SeqCst), 0);
600         }
601         assert_eq!(num_drops.load(Ordering::SeqCst), 1);
602     }
603
604     #[test]
605     fn test_into_inner_poison() {
606         let m = Arc::new(Mutex::new(NonCopy(10)));
607         let m2 = m.clone();
608         let _ = thread::spawn(move || {
609             let _lock = m2.lock().unwrap();
610             panic!("test panic in inner thread to poison mutex");
611         })
612         .join();
613
614         assert!(m.is_poisoned());
615         match Arc::try_unwrap(m).unwrap().into_inner() {
616             Err(e) => assert_eq!(e.into_inner(), NonCopy(10)),
617             Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x),
618         }
619     }
620
621     #[test]
622     fn test_get_mut() {
623         let mut m = Mutex::new(NonCopy(10));
624         *m.get_mut().unwrap() = NonCopy(20);
625         assert_eq!(m.into_inner().unwrap(), NonCopy(20));
626     }
627
628     #[test]
629     fn test_get_mut_poison() {
630         let m = Arc::new(Mutex::new(NonCopy(10)));
631         let m2 = m.clone();
632         let _ = thread::spawn(move || {
633             let _lock = m2.lock().unwrap();
634             panic!("test panic in inner thread to poison mutex");
635         })
636         .join();
637
638         assert!(m.is_poisoned());
639         match Arc::try_unwrap(m).unwrap().get_mut() {
640             Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)),
641             Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x),
642         }
643     }
644
645     #[test]
646     fn test_mutex_arc_condvar() {
647         let packet = Packet(Arc::new((Mutex::new(false), Condvar::new())));
648         let packet2 = Packet(packet.0.clone());
649         let (tx, rx) = channel();
650         let _t = thread::spawn(move || {
651             // wait until parent gets in
652             rx.recv().unwrap();
653             let &(ref lock, ref cvar) = &*packet2.0;
654             let mut lock = lock.lock().unwrap();
655             *lock = true;
656             cvar.notify_one();
657         });
658
659         let &(ref lock, ref cvar) = &*packet.0;
660         let mut lock = lock.lock().unwrap();
661         tx.send(()).unwrap();
662         assert!(!*lock);
663         while !*lock {
664             lock = cvar.wait(lock).unwrap();
665         }
666     }
667
668     #[test]
669     fn test_arc_condvar_poison() {
670         let packet = Packet(Arc::new((Mutex::new(1), Condvar::new())));
671         let packet2 = Packet(packet.0.clone());
672         let (tx, rx) = channel();
673
674         let _t = thread::spawn(move || -> () {
675             rx.recv().unwrap();
676             let &(ref lock, ref cvar) = &*packet2.0;
677             let _g = lock.lock().unwrap();
678             cvar.notify_one();
679             // Parent should fail when it wakes up.
680             panic!();
681         });
682
683         let &(ref lock, ref cvar) = &*packet.0;
684         let mut lock = lock.lock().unwrap();
685         tx.send(()).unwrap();
686         while *lock == 1 {
687             match cvar.wait(lock) {
688                 Ok(l) => {
689                     lock = l;
690                     assert_eq!(*lock, 1);
691                 }
692                 Err(..) => break,
693             }
694         }
695     }
696
697     #[test]
698     fn test_mutex_arc_poison() {
699         let arc = Arc::new(Mutex::new(1));
700         assert!(!arc.is_poisoned());
701         let arc2 = arc.clone();
702         let _ = thread::spawn(move || {
703             let lock = arc2.lock().unwrap();
704             assert_eq!(*lock, 2);
705         })
706         .join();
707         assert!(arc.lock().is_err());
708         assert!(arc.is_poisoned());
709     }
710
711     #[test]
712     fn test_mutex_arc_nested() {
713         // Tests nested mutexes and access
714         // to underlying data.
715         let arc = Arc::new(Mutex::new(1));
716         let arc2 = Arc::new(Mutex::new(arc));
717         let (tx, rx) = channel();
718         let _t = thread::spawn(move || {
719             let lock = arc2.lock().unwrap();
720             let lock2 = lock.lock().unwrap();
721             assert_eq!(*lock2, 1);
722             tx.send(()).unwrap();
723         });
724         rx.recv().unwrap();
725     }
726
727     #[test]
728     fn test_mutex_arc_access_in_unwind() {
729         let arc = Arc::new(Mutex::new(1));
730         let arc2 = arc.clone();
731         let _ = thread::spawn(move || -> () {
732             struct Unwinder {
733                 i: Arc<Mutex<i32>>,
734             }
735             impl Drop for Unwinder {
736                 fn drop(&mut self) {
737                     *self.i.lock().unwrap() += 1;
738                 }
739             }
740             let _u = Unwinder { i: arc2 };
741             panic!();
742         })
743         .join();
744         let lock = arc.lock().unwrap();
745         assert_eq!(*lock, 2);
746     }
747
748     #[test]
749     fn test_mutex_unsized() {
750         let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]);
751         {
752             let b = &mut *mutex.lock().unwrap();
753             b[0] = 4;
754             b[2] = 5;
755         }
756         let comp: &[i32] = &[4, 2, 5];
757         assert_eq!(&*mutex.lock().unwrap(), comp);
758     }
759 }