1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cell::UnsafeCell;
7 use crate::ops::{Deref, DerefMut};
9 use crate::sys_common::mutex as sys;
10 use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
12 /// A mutual exclusion primitive useful for protecting shared data
14 /// This mutex will block threads waiting for the lock to become available. The
15 /// mutex can also be statically initialized or created via a [`new`]
16 /// constructor. Each mutex has a type parameter which represents the data that
17 /// it is protecting. The data can only be accessed through the RAII guards
18 /// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
19 /// ever accessed when the mutex is locked.
23 /// The mutexes in this module implement a strategy called "poisoning" where a
24 /// mutex is considered poisoned whenever a thread panics while holding the
25 /// mutex. Once a mutex is poisoned, all other threads are unable to access the
26 /// data by default as it is likely tainted (some invariant is not being
29 /// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
30 /// [`Result`] which indicates whether a mutex has been poisoned or not. Most
31 /// usage of a mutex will simply [`unwrap()`] these results, propagating panics
32 /// among threads to ensure that a possibly invalid invariant is not witnessed.
34 /// A poisoned mutex, however, does not prevent all access to the underlying
35 /// data. The [`PoisonError`] type has an [`into_inner`] method which will return
36 /// the guard that would have otherwise been returned on a successful lock. This
37 /// allows access to the data, despite the lock being poisoned.
39 /// [`new`]: Self::new
40 /// [`lock`]: Self::lock
41 /// [`try_lock`]: Self::try_lock
42 /// [`unwrap()`]: Result::unwrap
43 /// [`PoisonError`]: super::PoisonError
44 /// [`into_inner`]: super::PoisonError::into_inner
49 /// use std::sync::{Arc, Mutex};
51 /// use std::sync::mpsc::channel;
53 /// const N: usize = 10;
55 /// // Spawn a few threads to increment a shared variable (non-atomically), and
56 /// // let the main thread know once all increments are done.
58 /// // Here we're using an Arc to share memory among threads, and the data inside
59 /// // the Arc is protected with a mutex.
60 /// let data = Arc::new(Mutex::new(0));
62 /// let (tx, rx) = channel();
64 /// let (data, tx) = (Arc::clone(&data), tx.clone());
65 /// thread::spawn(move || {
66 /// // The shared state can only be accessed once the lock is held.
67 /// // Our non-atomic increment is safe because we're the only thread
68 /// // which can access the shared state when the lock is held.
70 /// // We unwrap() the return value to assert that we are not expecting
71 /// // threads to ever fail while holding the lock.
72 /// let mut data = data.lock().unwrap();
75 /// tx.send(()).unwrap();
77 /// // the lock is unlocked here when `data` goes out of scope.
81 /// rx.recv().unwrap();
84 /// To recover from a poisoned mutex:
87 /// use std::sync::{Arc, Mutex};
90 /// let lock = Arc::new(Mutex::new(0_u32));
91 /// let lock2 = lock.clone();
93 /// let _ = thread::spawn(move || -> () {
94 /// // This thread will acquire the mutex first, unwrapping the result of
95 /// // `lock` because the lock has not been poisoned.
96 /// let _guard = lock2.lock().unwrap();
98 /// // This panic while holding the lock (`_guard` is in scope) will poison
103 /// // The lock is poisoned by this point, but the returned result can be
104 /// // pattern matched on to return the underlying guard on both branches.
105 /// let mut guard = match lock.lock() {
106 /// Ok(guard) => guard,
107 /// Err(poisoned) => poisoned.into_inner(),
113 /// It is sometimes necessary to manually drop the mutex guard to unlock it
114 /// sooner than the end of the enclosing scope.
117 /// use std::sync::{Arc, Mutex};
120 /// const N: usize = 3;
122 /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
123 /// let res_mutex = Arc::new(Mutex::new(0));
125 /// let mut threads = Vec::with_capacity(N);
126 /// (0..N).for_each(|_| {
127 /// let data_mutex_clone = Arc::clone(&data_mutex);
128 /// let res_mutex_clone = Arc::clone(&res_mutex);
130 /// threads.push(thread::spawn(move || {
131 /// let mut data = data_mutex_clone.lock().unwrap();
132 /// // This is the result of some important and long-ish work.
133 /// let result = data.iter().fold(0, |acc, x| acc + x * 2);
134 /// data.push(result);
136 /// *res_mutex_clone.lock().unwrap() += result;
140 /// let mut data = data_mutex.lock().unwrap();
141 /// // This is the result of some important and long-ish work.
142 /// let result = data.iter().fold(0, |acc, x| acc + x * 2);
143 /// data.push(result);
144 /// // We drop the `data` explicitly because it's not necessary anymore and the
145 /// // thread still has work to do. This allow other threads to start working on
146 /// // the data immediately, without waiting for the rest of the unrelated work
147 /// // to be done here.
149 /// // It's even more important here than in the threads because we `.join` the
150 /// // threads after that. If we had not dropped the mutex guard, a thread could
151 /// // be waiting forever for it, causing a deadlock.
153 /// // Here the mutex guard is not assigned to a variable and so, even if the
154 /// // scope does not end after this line, the mutex is still released: there is
156 /// *res_mutex.lock().unwrap() += result;
158 /// threads.into_iter().for_each(|thread| {
161 /// .expect("The thread creating or execution failed !")
164 /// assert_eq!(*res_mutex.lock().unwrap(), 800);
166 #[stable(feature = "rust1", since = "1.0.0")]
167 #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")]
168 pub struct Mutex<T: ?Sized> {
169 // Note that this mutex is in a *box*, not inlined into the struct itself.
170 // Once a native mutex has been used once, its address can never change (it
171 // can't be moved). This mutex type can be safely moved at any time, so to
172 // ensure that the native mutex is used correctly we box the inner mutex to
173 // give it a constant address.
174 inner: Box<sys::Mutex>,
175 poison: poison::Flag,
179 // these are the only places where `T: Send` matters; all other
180 // functionality works fine on a single thread.
181 #[stable(feature = "rust1", since = "1.0.0")]
182 unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
183 #[stable(feature = "rust1", since = "1.0.0")]
184 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
186 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
187 /// dropped (falls out of scope), the lock will be unlocked.
189 /// The data protected by the mutex can be accessed through this guard via its
190 /// [`Deref`] and [`DerefMut`] implementations.
192 /// This structure is created by the [`lock`] and [`try_lock`] methods on
195 /// [`lock`]: Mutex::lock
196 /// [`try_lock`]: Mutex::try_lock
197 #[must_use = "if unused the Mutex will immediately unlock"]
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub struct MutexGuard<'a, T: ?Sized + 'a> {
201 poison: poison::Guard,
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
206 #[stable(feature = "mutexguard", since = "1.19.0")]
207 unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
210 /// Creates a new mutex in an unlocked state ready for use.
215 /// use std::sync::Mutex;
217 /// let mutex = Mutex::new(0);
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn new(t: T) -> Mutex<T> {
222 inner: box sys::Mutex::new(),
223 poison: poison::Flag::new(),
224 data: UnsafeCell::new(t),
233 impl<T: ?Sized> Mutex<T> {
234 /// Acquires a mutex, blocking the current thread until it is able to do so.
236 /// This function will block the local thread until it is available to acquire
237 /// the mutex. Upon returning, the thread is the only thread with the lock
238 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
239 /// the guard goes out of scope, the mutex will be unlocked.
241 /// The exact behavior on locking a mutex in the thread which already holds
242 /// the lock is left unspecified. However, this function will not return on
243 /// the second call (it might panic or deadlock, for example).
247 /// If another user of this mutex panicked while holding the mutex, then
248 /// this call will return an error once the mutex is acquired.
252 /// This function might panic when called if the lock is already held by
253 /// the current thread.
258 /// use std::sync::{Arc, Mutex};
261 /// let mutex = Arc::new(Mutex::new(0));
262 /// let c_mutex = mutex.clone();
264 /// thread::spawn(move || {
265 /// *c_mutex.lock().unwrap() = 10;
266 /// }).join().expect("thread::spawn failed");
267 /// assert_eq!(*mutex.lock().unwrap(), 10);
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
272 self.inner.raw_lock();
273 MutexGuard::new(self)
277 /// Attempts to acquire this lock.
279 /// If the lock could not be acquired at this time, then [`Err`] is returned.
280 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
281 /// guard is dropped.
283 /// This function does not block.
287 /// If another user of this mutex panicked while holding the mutex, then
288 /// this call will return failure if the mutex would otherwise be
294 /// use std::sync::{Arc, Mutex};
297 /// let mutex = Arc::new(Mutex::new(0));
298 /// let c_mutex = mutex.clone();
300 /// thread::spawn(move || {
301 /// let mut lock = c_mutex.try_lock();
302 /// if let Ok(ref mut mutex) = lock {
305 /// println!("try_lock failed");
307 /// }).join().expect("thread::spawn failed");
308 /// assert_eq!(*mutex.lock().unwrap(), 10);
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
313 if self.inner.try_lock() {
314 Ok(MutexGuard::new(self)?)
316 Err(TryLockError::WouldBlock)
321 /// Determines whether the mutex is poisoned.
323 /// If another thread is active, the mutex can still become poisoned at any
324 /// time. You should not trust a `false` value for program correctness
325 /// without additional synchronization.
330 /// use std::sync::{Arc, Mutex};
333 /// let mutex = Arc::new(Mutex::new(0));
334 /// let c_mutex = mutex.clone();
336 /// let _ = thread::spawn(move || {
337 /// let _lock = c_mutex.lock().unwrap();
338 /// panic!(); // the mutex gets poisoned
340 /// assert_eq!(mutex.is_poisoned(), true);
343 #[stable(feature = "sync_poison", since = "1.2.0")]
344 pub fn is_poisoned(&self) -> bool {
348 /// Consumes this mutex, returning the underlying data.
352 /// If another user of this mutex panicked while holding the mutex, then
353 /// this call will return an error instead.
358 /// use std::sync::Mutex;
360 /// let mutex = Mutex::new(0);
361 /// assert_eq!(mutex.into_inner().unwrap(), 0);
363 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
364 pub fn into_inner(self) -> LockResult<T>
368 // We know statically that there are no outstanding references to
369 // `self` so there's no need to lock the inner mutex.
371 // To get the inner value, we'd like to call `data.into_inner()`,
372 // but because `Mutex` impl-s `Drop`, we can't move out of it, so
373 // we'll have to destructure it manually instead.
375 // Like `let Mutex { inner, poison, data } = self`.
376 let (inner, poison, data) = {
377 let Mutex { ref inner, ref poison, ref data } = self;
378 (ptr::read(inner), ptr::read(poison), ptr::read(data))
381 inner.destroy(); // Keep in sync with the `Drop` impl.
384 poison::map_result(poison.borrow(), |_| data.into_inner())
388 /// Returns a mutable reference to the underlying data.
390 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
391 /// take place -- the mutable borrow statically guarantees no locks exist.
395 /// If another user of this mutex panicked while holding the mutex, then
396 /// this call will return an error instead.
401 /// use std::sync::Mutex;
403 /// let mut mutex = Mutex::new(0);
404 /// *mutex.get_mut().unwrap() = 10;
405 /// assert_eq!(*mutex.lock().unwrap(), 10);
407 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
408 pub fn get_mut(&mut self) -> LockResult<&mut T> {
409 // We know statically that there are no other references to `self`, so
410 // there's no need to lock the inner mutex.
411 let data = unsafe { &mut *self.data.get() };
412 poison::map_result(self.poison.borrow(), |_| data)
416 #[stable(feature = "rust1", since = "1.0.0")]
417 unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
419 // This is actually safe b/c we know that there is no further usage of
420 // this mutex (it's up to the user to arrange for a mutex to get
421 // dropped, that's not our job)
423 // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
424 unsafe { self.inner.destroy() }
428 #[stable(feature = "mutex_from", since = "1.24.0")]
429 impl<T> From<T> for Mutex<T> {
430 /// Creates a new mutex in an unlocked state ready for use.
431 /// This is equivalent to [`Mutex::new`].
432 fn from(t: T) -> Self {
437 #[stable(feature = "mutex_default", since = "1.10.0")]
438 impl<T: ?Sized + Default> Default for Mutex<T> {
439 /// Creates a `Mutex<T>`, with the `Default` value for T.
440 fn default() -> Mutex<T> {
441 Mutex::new(Default::default())
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
448 match self.try_lock() {
449 Ok(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(),
450 Err(TryLockError::Poisoned(err)) => {
451 f.debug_struct("Mutex").field("data", &&**err.get_ref()).finish()
453 Err(TryLockError::WouldBlock) => {
454 struct LockedPlaceholder;
455 impl fmt::Debug for LockedPlaceholder {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 f.write_str("<locked>")
461 f.debug_struct("Mutex").field("data", &LockedPlaceholder).finish()
467 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
468 unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
469 poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
477 fn deref(&self) -> &T {
478 unsafe { &*self.lock.data.get() }
482 #[stable(feature = "rust1", since = "1.0.0")]
483 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
484 fn deref_mut(&mut self) -> &mut T {
485 unsafe { &mut *self.lock.data.get() }
489 #[stable(feature = "rust1", since = "1.0.0")]
490 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
494 self.lock.poison.done(&self.poison);
495 self.lock.inner.raw_unlock();
500 #[stable(feature = "std_debug", since = "1.16.0")]
501 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
502 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503 fmt::Debug::fmt(&**self, f)
507 #[stable(feature = "std_guard_impls", since = "1.20.0")]
508 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
518 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {