1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cell::UnsafeCell;
6 use crate::ops::{Deref, DerefMut};
7 use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
8 use crate::sys::locks as sys;
10 /// A mutual exclusion primitive useful for protecting shared data
12 /// This mutex will block threads waiting for the lock to become available. The
13 /// mutex can be created via a [`new`] constructor. Each mutex has a type parameter
14 /// which represents the data that it is protecting. The data can only be accessed
15 /// through the RAII guards returned from [`lock`] and [`try_lock`], which
16 /// guarantees that the data is only 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 = Arc::clone(&lock);
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")]
165 pub struct Mutex<T: ?Sized> {
167 poison: poison::Flag,
171 // these are the only places where `T: Send` matters; all other
172 // functionality works fine on a single thread.
173 #[stable(feature = "rust1", since = "1.0.0")]
174 unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
175 #[stable(feature = "rust1", since = "1.0.0")]
176 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
178 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
179 /// dropped (falls out of scope), the lock will be unlocked.
181 /// The data protected by the mutex can be accessed through this guard via its
182 /// [`Deref`] and [`DerefMut`] implementations.
184 /// This structure is created by the [`lock`] and [`try_lock`] methods on
187 /// [`lock`]: Mutex::lock
188 /// [`try_lock`]: Mutex::try_lock
189 #[must_use = "if unused the Mutex will immediately unlock"]
190 #[must_not_suspend = "holding a MutexGuard across suspend \
191 points can cause deadlocks, delays, \
192 and cause Futures to not implement `Send`"]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[clippy::has_significant_drop]
195 #[cfg_attr(not(test), rustc_diagnostic_item = "MutexGuard")]
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 #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
219 pub const fn new(t: T) -> Mutex<T> {
220 Mutex { inner: sys::Mutex::new(), poison: poison::Flag::new(), data: UnsafeCell::new(t) }
224 impl<T: ?Sized> Mutex<T> {
225 /// Acquires a mutex, blocking the current thread until it is able to do so.
227 /// This function will block the local thread until it is available to acquire
228 /// the mutex. Upon returning, the thread is the only thread with the lock
229 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
230 /// the guard goes out of scope, the mutex will be unlocked.
232 /// The exact behavior on locking a mutex in the thread which already holds
233 /// the lock is left unspecified. However, this function will not return on
234 /// the second call (it might panic or deadlock, for example).
238 /// If another user of this mutex panicked while holding the mutex, then
239 /// this call will return an error once the mutex is acquired.
243 /// This function might panic when called if the lock is already held by
244 /// the current thread.
249 /// use std::sync::{Arc, Mutex};
252 /// let mutex = Arc::new(Mutex::new(0));
253 /// let c_mutex = Arc::clone(&mutex);
255 /// thread::spawn(move || {
256 /// *c_mutex.lock().unwrap() = 10;
257 /// }).join().expect("thread::spawn failed");
258 /// assert_eq!(*mutex.lock().unwrap(), 10);
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
264 MutexGuard::new(self)
268 /// Attempts to acquire this lock.
270 /// If the lock could not be acquired at this time, then [`Err`] is returned.
271 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
272 /// guard is dropped.
274 /// This function does not block.
278 /// If another user of this mutex panicked while holding the mutex, then
279 /// this call will return the [`Poisoned`] error if the mutex would
280 /// otherwise be acquired.
282 /// If the mutex could not be acquired because it is already locked, then
283 /// this call will return the [`WouldBlock`] error.
285 /// [`Poisoned`]: TryLockError::Poisoned
286 /// [`WouldBlock`]: TryLockError::WouldBlock
291 /// use std::sync::{Arc, Mutex};
294 /// let mutex = Arc::new(Mutex::new(0));
295 /// let c_mutex = Arc::clone(&mutex);
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 /// Immediately drops the guard, and consequently unlocks the mutex.
320 /// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
321 /// Alternately, the guard will be automatically dropped when it goes out of scope.
324 /// #![feature(mutex_unlock)]
326 /// use std::sync::Mutex;
327 /// let mutex = Mutex::new(0);
329 /// let mut guard = mutex.lock().unwrap();
331 /// Mutex::unlock(guard);
333 #[unstable(feature = "mutex_unlock", issue = "81872")]
334 pub fn unlock(guard: MutexGuard<'_, T>) {
338 /// Determines whether the mutex is poisoned.
340 /// If another thread is active, the mutex can still become poisoned at any
341 /// time. You should not trust a `false` value for program correctness
342 /// without additional synchronization.
347 /// use std::sync::{Arc, Mutex};
350 /// let mutex = Arc::new(Mutex::new(0));
351 /// let c_mutex = Arc::clone(&mutex);
353 /// let _ = thread::spawn(move || {
354 /// let _lock = c_mutex.lock().unwrap();
355 /// panic!(); // the mutex gets poisoned
357 /// assert_eq!(mutex.is_poisoned(), true);
360 #[stable(feature = "sync_poison", since = "1.2.0")]
361 pub fn is_poisoned(&self) -> bool {
365 /// Clear the poisoned state from a mutex
367 /// If the mutex is poisoned, it will remain poisoned until this function is called. This
368 /// allows recovering from a poisoned state and marking that it has recovered. For example, if
369 /// the value is overwritten by a known-good value, then the mutex can be marked as
370 /// un-poisoned. Or possibly, the value could be inspected to determine if it is in a
371 /// consistent state, and if so the poison is removed.
376 /// #![feature(mutex_unpoison)]
378 /// use std::sync::{Arc, Mutex};
381 /// let mutex = Arc::new(Mutex::new(0));
382 /// let c_mutex = Arc::clone(&mutex);
384 /// let _ = thread::spawn(move || {
385 /// let _lock = c_mutex.lock().unwrap();
386 /// panic!(); // the mutex gets poisoned
389 /// assert_eq!(mutex.is_poisoned(), true);
390 /// let x = mutex.lock().unwrap_or_else(|mut e| {
391 /// **e.get_mut() = 1;
392 /// mutex.clear_poison();
395 /// assert_eq!(mutex.is_poisoned(), false);
396 /// assert_eq!(*x, 1);
399 #[unstable(feature = "mutex_unpoison", issue = "96469")]
400 pub fn clear_poison(&self) {
404 /// Consumes this mutex, returning the underlying data.
408 /// If another user of this mutex panicked while holding the mutex, then
409 /// this call will return an error instead.
414 /// use std::sync::Mutex;
416 /// let mutex = Mutex::new(0);
417 /// assert_eq!(mutex.into_inner().unwrap(), 0);
419 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
420 pub fn into_inner(self) -> LockResult<T>
424 let data = self.data.into_inner();
425 poison::map_result(self.poison.borrow(), |()| data)
428 /// Returns a mutable reference to the underlying data.
430 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
431 /// take place -- the mutable borrow statically guarantees no locks exist.
435 /// If another user of this mutex panicked while holding the mutex, then
436 /// this call will return an error instead.
441 /// use std::sync::Mutex;
443 /// let mut mutex = Mutex::new(0);
444 /// *mutex.get_mut().unwrap() = 10;
445 /// assert_eq!(*mutex.lock().unwrap(), 10);
447 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
448 pub fn get_mut(&mut self) -> LockResult<&mut T> {
449 let data = self.data.get_mut();
450 poison::map_result(self.poison.borrow(), |()| data)
454 #[stable(feature = "mutex_from", since = "1.24.0")]
455 impl<T> From<T> for Mutex<T> {
456 /// Creates a new mutex in an unlocked state ready for use.
457 /// This is equivalent to [`Mutex::new`].
458 fn from(t: T) -> Self {
463 #[stable(feature = "mutex_default", since = "1.10.0")]
464 impl<T: ?Sized + Default> Default for Mutex<T> {
465 /// Creates a `Mutex<T>`, with the `Default` value for T.
466 fn default() -> Mutex<T> {
467 Mutex::new(Default::default())
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 let mut d = f.debug_struct("Mutex");
475 match self.try_lock() {
477 d.field("data", &&*guard);
479 Err(TryLockError::Poisoned(err)) => {
480 d.field("data", &&**err.get_ref());
482 Err(TryLockError::WouldBlock) => {
483 struct LockedPlaceholder;
484 impl fmt::Debug for LockedPlaceholder {
485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486 f.write_str("<locked>")
489 d.field("data", &LockedPlaceholder);
492 d.field("poisoned", &self.poison.get());
493 d.finish_non_exhaustive()
497 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
498 unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
499 poison::map_result(lock.poison.guard(), |guard| MutexGuard { lock, poison: guard })
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
507 fn deref(&self) -> &T {
508 unsafe { &*self.lock.data.get() }
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
514 fn deref_mut(&mut self) -> &mut T {
515 unsafe { &mut *self.lock.data.get() }
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
524 self.lock.poison.done(&self.poison);
525 self.lock.inner.unlock();
530 #[stable(feature = "std_debug", since = "1.16.0")]
531 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
533 fmt::Debug::fmt(&**self, f)
537 #[stable(feature = "std_guard_impls", since = "1.20.0")]
538 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
539 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
548 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {