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_common::mutex 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 also be statically initialized or created via a [`new`]
14 /// constructor. Each mutex has a type parameter which represents the data that
15 /// it is protecting. The data can only be accessed through the RAII guards
16 /// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
17 /// ever accessed when the mutex is locked.
21 /// The mutexes in this module implement a strategy called "poisoning" where a
22 /// mutex is considered poisoned whenever a thread panics while holding the
23 /// mutex. Once a mutex is poisoned, all other threads are unable to access the
24 /// data by default as it is likely tainted (some invariant is not being
27 /// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
28 /// [`Result`] which indicates whether a mutex has been poisoned or not. Most
29 /// usage of a mutex will simply [`unwrap()`] these results, propagating panics
30 /// among threads to ensure that a possibly invalid invariant is not witnessed.
32 /// A poisoned mutex, however, does not prevent all access to the underlying
33 /// data. The [`PoisonError`] type has an [`into_inner`] method which will return
34 /// the guard that would have otherwise been returned on a successful lock. This
35 /// allows access to the data, despite the lock being poisoned.
37 /// [`new`]: Self::new
38 /// [`lock`]: Self::lock
39 /// [`try_lock`]: Self::try_lock
40 /// [`unwrap()`]: Result::unwrap
41 /// [`PoisonError`]: super::PoisonError
42 /// [`into_inner`]: super::PoisonError::into_inner
47 /// use std::sync::{Arc, Mutex};
49 /// use std::sync::mpsc::channel;
51 /// const N: usize = 10;
53 /// // Spawn a few threads to increment a shared variable (non-atomically), and
54 /// // let the main thread know once all increments are done.
56 /// // Here we're using an Arc to share memory among threads, and the data inside
57 /// // the Arc is protected with a mutex.
58 /// let data = Arc::new(Mutex::new(0));
60 /// let (tx, rx) = channel();
62 /// let (data, tx) = (Arc::clone(&data), tx.clone());
63 /// thread::spawn(move || {
64 /// // The shared state can only be accessed once the lock is held.
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.
68 /// // We unwrap() the return value to assert that we are not expecting
69 /// // threads to ever fail while holding the lock.
70 /// let mut data = data.lock().unwrap();
73 /// tx.send(()).unwrap();
75 /// // the lock is unlocked here when `data` goes out of scope.
79 /// rx.recv().unwrap();
82 /// To recover from a poisoned mutex:
85 /// use std::sync::{Arc, Mutex};
88 /// let lock = Arc::new(Mutex::new(0_u32));
89 /// let lock2 = Arc::clone(&lock);
91 /// let _ = thread::spawn(move || -> () {
92 /// // This thread will acquire the mutex first, unwrapping the result of
93 /// // `lock` because the lock has not been poisoned.
94 /// let _guard = lock2.lock().unwrap();
96 /// // This panic while holding the lock (`_guard` is in scope) will poison
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,
105 /// Err(poisoned) => poisoned.into_inner(),
111 /// It is sometimes necessary to manually drop the mutex guard to unlock it
112 /// sooner than the end of the enclosing scope.
115 /// use std::sync::{Arc, Mutex};
118 /// const N: usize = 3;
120 /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
121 /// let res_mutex = Arc::new(Mutex::new(0));
123 /// let mut threads = Vec::with_capacity(N);
124 /// (0..N).for_each(|_| {
125 /// let data_mutex_clone = Arc::clone(&data_mutex);
126 /// let res_mutex_clone = Arc::clone(&res_mutex);
128 /// threads.push(thread::spawn(move || {
129 /// let mut data = data_mutex_clone.lock().unwrap();
130 /// // This is the result of some important and long-ish work.
131 /// let result = data.iter().fold(0, |acc, x| acc + x * 2);
132 /// data.push(result);
134 /// *res_mutex_clone.lock().unwrap() += result;
138 /// let mut data = data_mutex.lock().unwrap();
139 /// // This is the result of some important and long-ish work.
140 /// let result = data.iter().fold(0, |acc, x| acc + x * 2);
141 /// data.push(result);
142 /// // We drop the `data` explicitly because it's not necessary anymore and the
143 /// // thread still has work to do. This allow other threads to start working on
144 /// // the data immediately, without waiting for the rest of the unrelated work
145 /// // to be done here.
147 /// // It's even more important here than in the threads because we `.join` the
148 /// // threads after that. If we had not dropped the mutex guard, a thread could
149 /// // be waiting forever for it, causing a deadlock.
151 /// // Here the mutex guard is not assigned to a variable and so, even if the
152 /// // scope does not end after this line, the mutex is still released: there is
154 /// *res_mutex.lock().unwrap() += result;
156 /// threads.into_iter().for_each(|thread| {
159 /// .expect("The thread creating or execution failed !")
162 /// assert_eq!(*res_mutex.lock().unwrap(), 800);
164 #[stable(feature = "rust1", since = "1.0.0")]
165 #[cfg_attr(not(test), rustc_diagnostic_item = "Mutex")]
166 pub struct Mutex<T: ?Sized> {
167 inner: sys::MovableMutex,
168 poison: poison::Flag,
172 // these are the only places where `T: Send` matters; all other
173 // functionality works fine on a single thread.
174 #[stable(feature = "rust1", since = "1.0.0")]
175 unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
176 #[stable(feature = "rust1", since = "1.0.0")]
177 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
179 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
180 /// dropped (falls out of scope), the lock will be unlocked.
182 /// The data protected by the mutex can be accessed through this guard via its
183 /// [`Deref`] and [`DerefMut`] implementations.
185 /// This structure is created by the [`lock`] and [`try_lock`] methods on
188 /// [`lock`]: Mutex::lock
189 /// [`try_lock`]: Mutex::try_lock
190 #[must_use = "if unused the Mutex will immediately unlock"]
191 #[must_not_suspend = "holding a MutexGuard across suspend \
192 points can cause deadlocks, delays, \
193 and cause Futures to not implement `Send`"]
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub struct MutexGuard<'a, T: ?Sized + 'a> {
197 poison: poison::Guard,
200 #[stable(feature = "rust1", since = "1.0.0")]
201 impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
202 #[stable(feature = "mutexguard", since = "1.19.0")]
203 unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
206 /// Creates a new mutex in an unlocked state ready for use.
211 /// use std::sync::Mutex;
213 /// let mutex = Mutex::new(0);
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn new(t: T) -> Mutex<T> {
218 inner: sys::MovableMutex::new(),
219 poison: poison::Flag::new(),
220 data: UnsafeCell::new(t),
225 impl<T: ?Sized> Mutex<T> {
226 /// Acquires a mutex, blocking the current thread until it is able to do so.
228 /// This function will block the local thread until it is available to acquire
229 /// the mutex. Upon returning, the thread is the only thread with the lock
230 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
231 /// the guard goes out of scope, the mutex will be unlocked.
233 /// The exact behavior on locking a mutex in the thread which already holds
234 /// the lock is left unspecified. However, this function will not return on
235 /// the second call (it might panic or deadlock, for example).
239 /// If another user of this mutex panicked while holding the mutex, then
240 /// this call will return an error once the mutex is acquired.
244 /// This function might panic when called if the lock is already held by
245 /// the current thread.
250 /// use std::sync::{Arc, Mutex};
253 /// let mutex = Arc::new(Mutex::new(0));
254 /// let c_mutex = Arc::clone(&mutex);
256 /// thread::spawn(move || {
257 /// *c_mutex.lock().unwrap() = 10;
258 /// }).join().expect("thread::spawn failed");
259 /// assert_eq!(*mutex.lock().unwrap(), 10);
261 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
264 self.inner.raw_lock();
265 MutexGuard::new(self)
269 /// Attempts to acquire this lock.
271 /// If the lock could not be acquired at this time, then [`Err`] is returned.
272 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
273 /// guard is dropped.
275 /// This function does not block.
279 /// If another user of this mutex panicked while holding the mutex, then
280 /// this call will return the [`Poisoned`] error if the mutex would
281 /// otherwise be acquired.
283 /// If the mutex could not be acquired because it is already locked, then
284 /// this call will return the [`WouldBlock`] error.
286 /// [`Poisoned`]: TryLockError::Poisoned
287 /// [`WouldBlock`]: TryLockError::WouldBlock
292 /// use std::sync::{Arc, Mutex};
295 /// let mutex = Arc::new(Mutex::new(0));
296 /// let c_mutex = Arc::clone(&mutex);
298 /// thread::spawn(move || {
299 /// let mut lock = c_mutex.try_lock();
300 /// if let Ok(ref mut mutex) = lock {
303 /// println!("try_lock failed");
305 /// }).join().expect("thread::spawn failed");
306 /// assert_eq!(*mutex.lock().unwrap(), 10);
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
311 if self.inner.try_lock() {
312 Ok(MutexGuard::new(self)?)
314 Err(TryLockError::WouldBlock)
319 /// Immediately drops the guard, and consequently unlocks the mutex.
321 /// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
322 /// Alternately, the guard will be automatically dropped when it goes out of scope.
325 /// #![feature(mutex_unlock)]
327 /// use std::sync::Mutex;
328 /// let mutex = Mutex::new(0);
330 /// let mut guard = mutex.lock().unwrap();
332 /// Mutex::unlock(guard);
334 #[unstable(feature = "mutex_unlock", issue = "81872")]
335 pub fn unlock(guard: MutexGuard<'_, T>) {
339 /// Determines whether the mutex is poisoned.
341 /// If another thread is active, the mutex can still become poisoned at any
342 /// time. You should not trust a `false` value for program correctness
343 /// without additional synchronization.
348 /// use std::sync::{Arc, Mutex};
351 /// let mutex = Arc::new(Mutex::new(0));
352 /// let c_mutex = Arc::clone(&mutex);
354 /// let _ = thread::spawn(move || {
355 /// let _lock = c_mutex.lock().unwrap();
356 /// panic!(); // the mutex gets poisoned
358 /// assert_eq!(mutex.is_poisoned(), true);
361 #[stable(feature = "sync_poison", since = "1.2.0")]
362 pub fn is_poisoned(&self) -> bool {
366 /// Consumes this mutex, returning the underlying data.
370 /// If another user of this mutex panicked while holding the mutex, then
371 /// this call will return an error instead.
376 /// use std::sync::Mutex;
378 /// let mutex = Mutex::new(0);
379 /// assert_eq!(mutex.into_inner().unwrap(), 0);
381 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
382 pub fn into_inner(self) -> LockResult<T>
386 let data = self.data.into_inner();
387 poison::map_result(self.poison.borrow(), |_| data)
390 /// Returns a mutable reference to the underlying data.
392 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
393 /// take place -- the mutable borrow statically guarantees no locks exist.
397 /// If another user of this mutex panicked while holding the mutex, then
398 /// this call will return an error instead.
403 /// use std::sync::Mutex;
405 /// let mut mutex = Mutex::new(0);
406 /// *mutex.get_mut().unwrap() = 10;
407 /// assert_eq!(*mutex.lock().unwrap(), 10);
409 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
410 pub fn get_mut(&mut self) -> LockResult<&mut T> {
411 let data = self.data.get_mut();
412 poison::map_result(self.poison.borrow(), |_| data)
416 #[stable(feature = "mutex_from", since = "1.24.0")]
417 impl<T> From<T> for Mutex<T> {
418 /// Creates a new mutex in an unlocked state ready for use.
419 /// This is equivalent to [`Mutex::new`].
420 fn from(t: T) -> Self {
425 #[stable(feature = "mutex_default", since = "1.10.0")]
426 impl<T: ?Sized + Default> Default for Mutex<T> {
427 /// Creates a `Mutex<T>`, with the `Default` value for T.
428 fn default() -> Mutex<T> {
429 Mutex::new(Default::default())
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436 let mut d = f.debug_struct("Mutex");
437 match self.try_lock() {
439 d.field("data", &&*guard);
441 Err(TryLockError::Poisoned(err)) => {
442 d.field("data", &&**err.get_ref());
444 Err(TryLockError::WouldBlock) => {
445 struct LockedPlaceholder;
446 impl fmt::Debug for LockedPlaceholder {
447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448 f.write_str("<locked>")
451 d.field("data", &LockedPlaceholder);
454 d.field("poisoned", &self.poison.get());
455 d.finish_non_exhaustive()
459 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
460 unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
461 poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
469 fn deref(&self) -> &T {
470 unsafe { &*self.lock.data.get() }
474 #[stable(feature = "rust1", since = "1.0.0")]
475 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
476 fn deref_mut(&mut self) -> &mut T {
477 unsafe { &mut *self.lock.data.get() }
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
486 self.lock.poison.done(&self.poison);
487 self.lock.inner.raw_unlock();
492 #[stable(feature = "std_debug", since = "1.16.0")]
493 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495 fmt::Debug::fmt(&**self, f)
499 #[stable(feature = "std_guard_impls", since = "1.20.0")]
500 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::MovableMutex {
510 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {