1 use crate::cell::UnsafeCell;
4 use crate::ops::{Deref, DerefMut};
6 use crate::sys_common::mutex as sys;
7 use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
9 /// A mutual exclusion primitive useful for protecting shared data
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.
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
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.
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.
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
46 /// use std::sync::{Arc, Mutex};
48 /// use std::sync::mpsc::channel;
50 /// const N: usize = 10;
52 /// // Spawn a few threads to increment a shared variable (non-atomically), and
53 /// // let the main thread know once all increments are done.
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));
59 /// let (tx, rx) = channel();
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.
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();
72 /// tx.send(()).unwrap();
74 /// // the lock is unlocked here when `data` goes out of scope.
78 /// rx.recv().unwrap();
81 /// To recover from a poisoned mutex:
84 /// use std::sync::{Arc, Mutex};
87 /// let lock = Arc::new(Mutex::new(0_u32));
88 /// let lock2 = lock.clone();
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();
95 /// // This panic while holding the lock (`_guard` is in scope) will poison
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(),
110 /// It is sometimes necessary to manually drop the mutex guard to unlock it
111 /// sooner than the end of the enclosing scope.
114 /// use std::sync::{Arc, Mutex};
117 /// const N: usize = 3;
119 /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
120 /// let res_mutex = Arc::new(Mutex::new(0));
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);
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);
133 /// *res_mutex_clone.lock().unwrap() += result;
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.
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.
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
153 /// *res_mutex.lock().unwrap() += result;
155 /// threads.into_iter().for_each(|thread| {
158 /// .expect("The thread creating or execution failed !")
161 /// assert_eq!(*res_mutex.lock().unwrap(), 800);
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,
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> {}
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.
186 /// The data protected by the mutex can be accessed through this guard via its
187 /// [`Deref`] and [`DerefMut`] implementations.
189 /// This structure is created by the [`lock`] and [`try_lock`] methods on
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> {
198 poison: poison::Guard,
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> {}
207 /// Creates a new mutex in an unlocked state ready for use.
212 /// use std::sync::Mutex;
214 /// let mutex = Mutex::new(0);
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn new(t: T) -> Mutex<T> {
219 inner: box sys::Mutex::new(),
220 poison: poison::Flag::new(),
221 data: UnsafeCell::new(t),
230 impl<T: ?Sized> Mutex<T> {
231 /// Acquires a mutex, blocking the current thread until it is able to do so.
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.
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).
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.
249 /// This function might panic when called if the lock is already held by
250 /// the current thread.
255 /// use std::sync::{Arc, Mutex};
258 /// let mutex = Arc::new(Mutex::new(0));
259 /// let c_mutex = mutex.clone();
261 /// thread::spawn(move || {
262 /// *c_mutex.lock().unwrap() = 10;
263 /// }).join().expect("thread::spawn failed");
264 /// assert_eq!(*mutex.lock().unwrap(), 10);
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
269 self.inner.raw_lock();
270 MutexGuard::new(self)
274 /// Attempts to acquire this lock.
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.
280 /// This function does not block.
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
291 /// use std::sync::{Arc, Mutex};
294 /// let mutex = Arc::new(Mutex::new(0));
295 /// let c_mutex = mutex.clone();
297 /// thread::spawn(move || {
298 /// let mut lock = c_mutex.try_lock();
299 /// if let Ok(ref mut mutex) = lock {
302 /// println!("try_lock failed");
304 /// }).join().expect("thread::spawn failed");
305 /// assert_eq!(*mutex.lock().unwrap(), 10);
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
310 if self.inner.try_lock() {
311 Ok(MutexGuard::new(self)?)
313 Err(TryLockError::WouldBlock)
318 /// Determines whether the mutex is poisoned.
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.
327 /// use std::sync::{Arc, Mutex};
330 /// let mutex = Arc::new(Mutex::new(0));
331 /// let c_mutex = mutex.clone();
333 /// let _ = thread::spawn(move || {
334 /// let _lock = c_mutex.lock().unwrap();
335 /// panic!(); // the mutex gets poisoned
337 /// assert_eq!(mutex.is_poisoned(), true);
340 #[stable(feature = "sync_poison", since = "1.2.0")]
341 pub fn is_poisoned(&self) -> bool {
345 /// Consumes this mutex, returning the underlying data.
349 /// If another user of this mutex panicked while holding the mutex, then
350 /// this call will return an error instead.
355 /// use std::sync::Mutex;
357 /// let mutex = Mutex::new(0);
358 /// assert_eq!(mutex.into_inner().unwrap(), 0);
360 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
361 pub fn into_inner(self) -> LockResult<T>
365 // We know statically that there are no outstanding references to
366 // `self` so there's no need to lock the inner mutex.
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.
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))
378 inner.destroy(); // Keep in sync with the `Drop` impl.
381 poison::map_result(poison.borrow(), |_| data.into_inner())
385 /// Returns a mutable reference to the underlying data.
387 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
388 /// take place -- the mutable borrow statically guarantees no locks exist.
392 /// If another user of this mutex panicked while holding the mutex, then
393 /// this call will return an error instead.
398 /// use std::sync::Mutex;
400 /// let mut mutex = Mutex::new(0);
401 /// *mutex.get_mut().unwrap() = 10;
402 /// assert_eq!(*mutex.lock().unwrap(), 10);
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)
413 #[stable(feature = "rust1", since = "1.0.0")]
414 unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
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)
420 // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
421 unsafe { self.inner.destroy() }
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 {
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())
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()
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>")
458 f.debug_struct("Mutex").field("data", &LockedPlaceholder).finish()
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 })
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
474 fn deref(&self) -> &T {
475 unsafe { &*self.lock.data.get() }
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() }
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
491 self.lock.poison.done(&self.poison);
492 self.lock.inner.raw_unlock();
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)
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 {
511 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
515 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
519 #[cfg(all(test, not(target_os = "emscripten")))]
521 use crate::sync::atomic::{AtomicUsize, Ordering};
522 use crate::sync::mpsc::channel;
523 use crate::sync::{Arc, Condvar, Mutex};
526 struct Packet<T>(Arc<(Mutex<T>, Condvar)>);
528 #[derive(Eq, PartialEq, Debug)]
533 let m = Mutex::new(());
534 drop(m.lock().unwrap());
535 drop(m.lock().unwrap());
543 let m = Arc::new(Mutex::new(0));
545 fn inc(m: &Mutex<u32>) {
547 *m.lock().unwrap() += 1;
551 let (tx, rx) = channel();
553 let tx2 = tx.clone();
555 thread::spawn(move || {
557 tx2.send(()).unwrap();
559 let tx2 = tx.clone();
561 thread::spawn(move || {
563 tx2.send(()).unwrap();
571 assert_eq!(*m.lock().unwrap(), J * K * 2);
576 let m = Mutex::new(());
577 *m.try_lock().unwrap() = ();
581 fn test_into_inner() {
582 let m = Mutex::new(NonCopy(10));
583 assert_eq!(m.into_inner().unwrap(), NonCopy(10));
587 fn test_into_inner_drop() {
588 struct Foo(Arc<AtomicUsize>);
591 self.0.fetch_add(1, Ordering::SeqCst);
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);
598 let _inner = m.into_inner().unwrap();
599 assert_eq!(num_drops.load(Ordering::SeqCst), 0);
601 assert_eq!(num_drops.load(Ordering::SeqCst), 1);
605 fn test_into_inner_poison() {
606 let m = Arc::new(Mutex::new(NonCopy(10)));
608 let _ = thread::spawn(move || {
609 let _lock = m2.lock().unwrap();
610 panic!("test panic in inner thread to poison mutex");
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),
623 let mut m = Mutex::new(NonCopy(10));
624 *m.get_mut().unwrap() = NonCopy(20);
625 assert_eq!(m.into_inner().unwrap(), NonCopy(20));
629 fn test_get_mut_poison() {
630 let m = Arc::new(Mutex::new(NonCopy(10)));
632 let _ = thread::spawn(move || {
633 let _lock = m2.lock().unwrap();
634 panic!("test panic in inner thread to poison mutex");
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),
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
653 let &(ref lock, ref cvar) = &*packet2.0;
654 let mut lock = lock.lock().unwrap();
659 let &(ref lock, ref cvar) = &*packet.0;
660 let mut lock = lock.lock().unwrap();
661 tx.send(()).unwrap();
664 lock = cvar.wait(lock).unwrap();
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();
674 let _t = thread::spawn(move || -> () {
676 let &(ref lock, ref cvar) = &*packet2.0;
677 let _g = lock.lock().unwrap();
679 // Parent should fail when it wakes up.
683 let &(ref lock, ref cvar) = &*packet.0;
684 let mut lock = lock.lock().unwrap();
685 tx.send(()).unwrap();
687 match cvar.wait(lock) {
690 assert_eq!(*lock, 1);
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);
707 assert!(arc.lock().is_err());
708 assert!(arc.is_poisoned());
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();
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 || -> () {
735 impl Drop for Unwinder {
737 *self.i.lock().unwrap() += 1;
740 let _u = Unwinder { i: arc2 };
744 let lock = arc.lock().unwrap();
745 assert_eq!(*lock, 2);
749 fn test_mutex_unsized() {
750 let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]);
752 let b = &mut *mutex.lock().unwrap();
756 let comp: &[i32] = &[4, 2, 5];
757 assert_eq!(&*mutex.lock().unwrap(), comp);