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