Skip to main content

std/sync/poison/
mutex.rs

1use crate::cell::UnsafeCell;
2use crate::fmt;
3use crate::marker::PhantomData;
4use crate::mem::{self, ManuallyDrop};
5use crate::ops::{Deref, DerefMut};
6use crate::ptr::NonNull;
7use crate::sync::{LockResult, PoisonError, TryLockError, TryLockResult, poison};
8use crate::sys::sync as sys;
9
10/// A mutual exclusion primitive useful for protecting shared data
11///
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.
17///
18/// # Poisoning
19///
20/// The mutexes in this module implement a strategy called "poisoning" where a
21/// mutex becomes poisoned if it recognizes that the thread holding it has
22/// panicked.
23///
24/// Once a mutex is poisoned, all other threads are unable to access the data by
25/// default as it is likely tainted (some invariant is not being upheld). For a
26/// 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.
30///
31/// Poisoning is only advisory: the [`PoisonError`] type has an [`into_inner`]
32/// method which will return the guard that would have otherwise been returned
33/// on a successful lock. This allows access to the data, despite the lock being
34/// poisoned.
35///
36/// In addition, the panic detection is not ideal, so even unpoisoned mutexes
37/// need to be handled with care, since certain panics may have been skipped.
38/// Here is a non-exhaustive list of situations where this might occur:
39///
40/// - If a mutex is locked while a panic is underway, e.g. within a [`Drop`]
41///   implementation or a [panic hook], panicking for the second time while the
42///   lock is held will leave the mutex unpoisoned. Note that while double panic
43///   usually aborts the program, [`catch_unwind`] can prevent this.
44///
45/// - Locking and unlocking the mutex across different panic contexts, e.g. by
46///   storing the guard to a [`Cell`] within [`Drop::drop`] and accessing it
47///   outside, or vice versa, can affect poisoning status in an unexpected way.
48///
49/// - Foreign exceptions do not currently trigger poisoning even in absence of
50///   other panics.
51///
52/// While this rarely happens in realistic code, `unsafe` code cannot rely on
53/// poisoning for soundness, since the behavior of poisoning can depend on
54/// outside context. Here's an example of **incorrect** use of poisoning:
55///
56/// ```rust
57/// use std::sync::Mutex;
58///
59/// struct MutexBox<T> {
60///     data: Mutex<*mut T>,
61/// }
62///
63/// impl<T> MutexBox<T> {
64///     pub fn new(value: T) -> Self {
65///         Self {
66///             data: Mutex::new(Box::into_raw(Box::new(value))),
67///         }
68///     }
69///
70///     pub fn replace_with(&self, f: impl FnOnce(T) -> T) {
71///         let ptr = self.data.lock().expect("`Mutex` should not be poisoned");
72///         // While `f` is running, the data is moved out of `*ptr`. If `f`
73///         // panics, `*ptr` keeps pointing at a dropped value. The intention
74///         // is that this will poison the mutex, so the following calls to
75///         // `replace_with` will panic without reading `*ptr`. But since
76///         // poisoning is not guaranteed to occur if this is run from a panic
77///         // hook, this can lead to use-after-free.
78///         unsafe {
79///             (*ptr).write(f((*ptr).read()));
80///         }
81///     }
82/// }
83/// ```
84///
85/// [`new`]: Self::new
86/// [`lock`]: Self::lock
87/// [`try_lock`]: Self::try_lock
88/// [`unwrap()`]: Result::unwrap
89/// [`PoisonError`]: super::PoisonError
90/// [`into_inner`]: super::PoisonError::into_inner
91/// [panic hook]: crate::panic::set_hook
92/// [`catch_unwind`]: crate::panic::catch_unwind
93/// [`Cell`]: crate::cell::Cell
94///
95/// # Examples
96///
97/// ```
98/// use std::sync::{Arc, Mutex};
99/// use std::thread;
100/// use std::sync::mpsc::channel;
101///
102/// const N: usize = 10;
103///
104/// // Spawn a few threads to increment a shared variable (non-atomically), and
105/// // let the main thread know once all increments are done.
106/// //
107/// // Here we're using an Arc to share memory among threads, and the data inside
108/// // the Arc is protected with a mutex.
109/// let data = Arc::new(Mutex::new(0));
110///
111/// let (tx, rx) = channel();
112/// for _ in 0..N {
113///     let (data, tx) = (Arc::clone(&data), tx.clone());
114///     thread::spawn(move || {
115///         // The shared state can only be accessed once the lock is held.
116///         // Our non-atomic increment is safe because we're the only thread
117///         // which can access the shared state when the lock is held.
118///         //
119///         // We unwrap() the return value to assert that we are not expecting
120///         // threads to ever fail while holding the lock.
121///         let mut data = data.lock().unwrap();
122///         *data += 1;
123///         if *data == N {
124///             tx.send(()).unwrap();
125///         }
126///         // the lock is unlocked here when `data` goes out of scope.
127///     });
128/// }
129///
130/// rx.recv().unwrap();
131/// ```
132///
133/// To recover from a poisoned mutex:
134///
135/// ```
136/// use std::sync::{Arc, Mutex};
137/// use std::thread;
138///
139/// let lock = Arc::new(Mutex::new(0_u32));
140/// let lock2 = Arc::clone(&lock);
141///
142/// let _ = thread::spawn(move || -> () {
143///     // This thread will acquire the mutex first, unwrapping the result of
144///     // `lock` because the lock has not been poisoned.
145///     let _guard = lock2.lock().unwrap();
146///
147///     // This panic while holding the lock (`_guard` is in scope) will poison
148///     // the mutex.
149///     panic!();
150/// }).join();
151///
152/// // The lock is poisoned by this point, but the returned result can be
153/// // pattern matched on to return the underlying guard on both branches.
154/// let mut guard = match lock.lock() {
155///     Ok(guard) => guard,
156///     Err(poisoned) => poisoned.into_inner(),
157/// };
158///
159/// *guard += 1;
160/// ```
161///
162/// To unlock a mutex guard sooner than the end of the enclosing scope,
163/// either create an inner scope or drop the guard manually.
164///
165/// ```
166/// use std::sync::{Arc, Mutex};
167/// use std::thread;
168///
169/// const N: usize = 3;
170///
171/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
172/// let res_mutex = Arc::new(Mutex::new(0));
173///
174/// let mut threads = Vec::with_capacity(N);
175/// (0..N).for_each(|_| {
176///     let data_mutex_clone = Arc::clone(&data_mutex);
177///     let res_mutex_clone = Arc::clone(&res_mutex);
178///
179///     threads.push(thread::spawn(move || {
180///         // Here we use a block to limit the lifetime of the lock guard.
181///         let result = {
182///             let mut data = data_mutex_clone.lock().unwrap();
183///             // This is the result of some important and long-ish work.
184///             let result = data.iter().fold(0, |acc, x| acc + x * 2);
185///             data.push(result);
186///             result
187///             // The mutex guard gets dropped here, together with any other values
188///             // created in the critical section.
189///         };
190///         // The guard created here is a temporary dropped at the end of the statement, i.e.
191///         // the lock would not remain being held even if the thread did some additional work.
192///         *res_mutex_clone.lock().unwrap() += result;
193///     }));
194/// });
195///
196/// let mut data = data_mutex.lock().unwrap();
197/// // This is the result of some important and long-ish work.
198/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
199/// data.push(result);
200/// // We drop the `data` explicitly because it's not necessary anymore and the
201/// // thread still has work to do. This allows other threads to start working on
202/// // the data immediately, without waiting for the rest of the unrelated work
203/// // to be done here.
204/// //
205/// // It's even more important here than in the threads because we `.join` the
206/// // threads after that. If we had not dropped the mutex guard, a thread could
207/// // be waiting forever for it, causing a deadlock.
208/// // As in the threads, a block could have been used instead of calling the
209/// // `drop` function.
210/// drop(data);
211/// // Here the mutex guard is not assigned to a variable and so, even if the
212/// // scope does not end after this line, the mutex is still released: there is
213/// // no deadlock.
214/// *res_mutex.lock().unwrap() += result;
215///
216/// threads.into_iter().for_each(|thread| {
217///     thread
218///         .join()
219///         .expect("Thread creation or execution should not fail")
220/// });
221///
222/// assert_eq!(*res_mutex.lock().unwrap(), 800);
223/// ```
224///
225#[stable(feature = "rust1", since = "1.0.0")]
226#[cfg_attr(not(test), rustc_diagnostic_item = "Mutex")]
227pub struct Mutex<#[rustc_assert_variance(invariant)] T: ?Sized> {
228    inner: sys::Mutex,
229    poison: poison::Flag,
230    data: UnsafeCell<T>,
231}
232
233/// `T` must be `Send` for a [`Mutex`] to be `Send` because it is possible to acquire
234/// the owned `T` from the `Mutex` via [`into_inner`].
235///
236/// [`into_inner`]: Mutex::into_inner
237#[stable(feature = "rust1", since = "1.0.0")]
238unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
239
240/// `T` must be `Send` for [`Mutex`] to be `Sync`.
241/// This ensures that the protected data can be accessed safely from multiple threads
242/// without causing data races or other unsafe behavior.
243///
244/// [`Mutex<T>`] provides mutable access to `T` to one thread at a time. However, it's essential
245/// for `T` to be `Send` because it's not safe for non-`Send` structures to be accessed in
246/// this manner. For instance, consider [`Rc`], a non-atomic reference counted smart pointer,
247/// which is not `Send`. With `Rc`, we can have multiple copies pointing to the same heap
248/// allocation with a non-atomic reference count. If we were to use `Mutex<Rc<_>>`, it would
249/// only protect one instance of `Rc` from shared access, leaving other copies vulnerable
250/// to potential data races.
251///
252/// Also note that it is not necessary for `T` to be `Sync` as `&T` is only made available
253/// to one thread at a time if `T` is not `Sync`.
254///
255/// [`Rc`]: crate::rc::Rc
256#[stable(feature = "rust1", since = "1.0.0")]
257unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
258
259/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
260/// dropped (falls out of scope), the lock will be unlocked.
261///
262/// The data protected by the mutex can be accessed through this guard via its
263/// [`Deref`] and [`DerefMut`] implementations.
264///
265/// This structure is created by the [`lock`] and [`try_lock`] methods on
266/// [`Mutex`].
267///
268/// [`lock`]: Mutex::lock
269/// [`try_lock`]: Mutex::try_lock
270#[must_use = "if unused the Mutex will immediately unlock"]
271#[must_not_suspend = "holding a MutexGuard across suspend \
272                      points can cause deadlocks, delays, \
273                      and cause Futures to not implement `Send`"]
274#[stable(feature = "rust1", since = "1.0.0")]
275#[clippy::has_significant_drop]
276#[cfg_attr(not(test), rustc_diagnostic_item = "MutexGuard")]
277pub struct MutexGuard<
278    #[rustc_assert_variance(covariant)] 'a,
279    #[rustc_assert_variance(invariant)] T: ?Sized + 'a,
280> {
281    lock: &'a Mutex<T>,
282    poison: poison::Guard,
283}
284
285/// A [`MutexGuard`] is not `Send` to maximize platform portability.
286///
287/// On platforms that use POSIX threads (commonly referred to as pthreads) there is a requirement to
288/// release mutex locks on the same thread they were acquired.
289/// For this reason, [`MutexGuard`] must not implement `Send` to prevent it being dropped from
290/// another thread.
291#[stable(feature = "rust1", since = "1.0.0")]
292impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
293
294/// `T` must be `Sync` for a [`MutexGuard<T>`] to be `Sync`
295/// because it is possible to get a `&T` from `&MutexGuard` (via `Deref`).
296#[stable(feature = "mutexguard", since = "1.19.0")]
297unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
298
299/// An RAII mutex guard returned by `MutexGuard::map`, which can point to a
300/// subfield of the protected data. When this structure is dropped (falls out
301/// of scope), the lock will be unlocked.
302///
303/// The main difference between `MappedMutexGuard` and [`MutexGuard`] is that the
304/// former cannot be used with [`Condvar`], since that
305/// could introduce soundness issues if the locked object is modified by another
306/// thread while the `Mutex` is unlocked.
307///
308/// The data protected by the mutex can be accessed through this guard via its
309/// [`Deref`] and [`DerefMut`] implementations.
310///
311/// This structure is created by the [`map`] and [`filter_map`] methods on
312/// [`MutexGuard`].
313///
314/// [`map`]: MutexGuard::map
315/// [`filter_map`]: MutexGuard::filter_map
316/// [`Condvar`]: crate::sync::Condvar
317#[must_use = "if unused the Mutex will immediately unlock"]
318#[must_not_suspend = "holding a MappedMutexGuard across suspend \
319                      points can cause deadlocks, delays, \
320                      and cause Futures to not implement `Send`"]
321#[unstable(feature = "mapped_lock_guards", issue = "117108")]
322#[clippy::has_significant_drop]
323pub struct MappedMutexGuard<
324    #[rustc_assert_variance(covariant)] 'a,
325    #[rustc_assert_variance(invariant)] T: ?Sized + 'a,
326> {
327    // NB: we use a pointer instead of `&'a mut T` to avoid `noalias` violations, because a
328    // `MappedMutexGuard` argument doesn't hold uniqueness for its whole scope, only until it drops.
329    // `NonNull` is covariant over `T`, so we add a `PhantomData<&'a mut T>` field
330    // below for the correct variance over `T` (invariance).
331    data: NonNull<T>,
332    inner: &'a sys::Mutex,
333    poison_flag: &'a poison::Flag,
334    poison: poison::Guard,
335    _variance: PhantomData<&'a mut T>,
336}
337
338#[unstable(feature = "mapped_lock_guards", issue = "117108")]
339impl<T: ?Sized> !Send for MappedMutexGuard<'_, T> {}
340#[unstable(feature = "mapped_lock_guards", issue = "117108")]
341unsafe impl<T: ?Sized + Sync> Sync for MappedMutexGuard<'_, T> {}
342
343impl<T> Mutex<T> {
344    /// Creates a new mutex in an unlocked state ready for use.
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// use std::sync::Mutex;
350    ///
351    /// let mutex = Mutex::new(0);
352    /// ```
353    #[stable(feature = "rust1", since = "1.0.0")]
354    #[rustc_const_stable(feature = "const_locks", since = "1.63.0")]
355    #[inline]
356    pub const fn new(t: T) -> Mutex<T> {
357        Mutex { inner: sys::Mutex::new(), poison: poison::Flag::new(), data: UnsafeCell::new(t) }
358    }
359
360    /// Returns the contained value by cloning it.
361    ///
362    /// # Errors
363    ///
364    /// If another user of this mutex panicked while holding the mutex, then
365    /// this call will return an error instead.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// #![feature(lock_value_accessors)]
371    ///
372    /// use std::sync::Mutex;
373    ///
374    /// let mut mutex = Mutex::new(7);
375    ///
376    /// assert_eq!(mutex.get_cloned().unwrap(), 7);
377    /// ```
378    #[unstable(feature = "lock_value_accessors", issue = "133407")]
379    pub fn get_cloned(&self) -> Result<T, PoisonError<()>>
380    where
381        T: Clone,
382    {
383        match self.lock() {
384            Ok(guard) => Ok((*guard).clone()),
385            Err(_) => Err(PoisonError::new(())),
386        }
387    }
388
389    /// Sets the contained value.
390    ///
391    /// # Errors
392    ///
393    /// If another user of this mutex panicked while holding the mutex, then
394    /// this call will return an error containing the provided `value` instead.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// #![feature(lock_value_accessors)]
400    ///
401    /// use std::sync::Mutex;
402    ///
403    /// let mut mutex = Mutex::new(7);
404    ///
405    /// assert_eq!(mutex.get_cloned().unwrap(), 7);
406    /// mutex.set(11).unwrap();
407    /// assert_eq!(mutex.get_cloned().unwrap(), 11);
408    /// ```
409    #[unstable(feature = "lock_value_accessors", issue = "133407")]
410    #[rustc_should_not_be_called_on_const_items]
411    pub fn set(&self, value: T) -> Result<(), PoisonError<T>> {
412        if mem::needs_drop::<T>() {
413            // If the contained value has non-trivial destructor, we
414            // call that destructor after the lock being released.
415            self.replace(value).map(drop)
416        } else {
417            match self.lock() {
418                Ok(mut guard) => {
419                    *guard = value;
420
421                    Ok(())
422                }
423                Err(_) => Err(PoisonError::new(value)),
424            }
425        }
426    }
427
428    /// Replaces the contained value with `value`, and returns the old contained value.
429    ///
430    /// # Errors
431    ///
432    /// If another user of this mutex panicked while holding the mutex, then
433    /// this call will return an error containing the provided `value` instead.
434    ///
435    /// # Examples
436    ///
437    /// ```
438    /// #![feature(lock_value_accessors)]
439    ///
440    /// use std::sync::Mutex;
441    ///
442    /// let mut mutex = Mutex::new(7);
443    ///
444    /// assert_eq!(mutex.replace(11).unwrap(), 7);
445    /// assert_eq!(mutex.get_cloned().unwrap(), 11);
446    /// ```
447    #[unstable(feature = "lock_value_accessors", issue = "133407")]
448    #[rustc_should_not_be_called_on_const_items]
449    pub fn replace(&self, value: T) -> LockResult<T> {
450        match self.lock() {
451            Ok(mut guard) => Ok(mem::replace(&mut *guard, value)),
452            Err(_) => Err(PoisonError::new(value)),
453        }
454    }
455}
456
457impl<T: ?Sized> Mutex<T> {
458    /// Acquires a mutex, blocking the current thread until it is able to do so.
459    ///
460    /// This function will block the local thread until it is available to acquire
461    /// the mutex. Upon returning, the thread is the only thread with the lock
462    /// held. An RAII guard is returned to allow scoped unlock of the lock. When
463    /// the guard goes out of scope, the mutex will be unlocked.
464    ///
465    /// The exact behavior on locking a mutex in the thread which already holds
466    /// the lock is left unspecified. However, this function will not return on
467    /// the second call (it might panic or deadlock, for example).
468    ///
469    /// # Errors
470    ///
471    /// If another user of this mutex panicked while holding the mutex, then
472    /// this call will return an error once the mutex is acquired. The acquired
473    /// mutex guard will be contained in the returned error.
474    ///
475    /// # Panics
476    ///
477    /// This function might panic when called if the lock is already held by
478    /// the current thread.
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// use std::sync::{Arc, Mutex};
484    /// use std::thread;
485    ///
486    /// let mutex = Arc::new(Mutex::new(0));
487    /// let c_mutex = Arc::clone(&mutex);
488    ///
489    /// thread::spawn(move || {
490    ///     *c_mutex.lock().unwrap() = 10;
491    /// }).join().expect("`thread::spawn` should not fail");
492    /// assert_eq!(*mutex.lock().unwrap(), 10);
493    /// ```
494    #[stable(feature = "rust1", since = "1.0.0")]
495    #[rustc_should_not_be_called_on_const_items]
496    pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
497        unsafe {
498            self.inner.lock();
499            MutexGuard::new(self)
500        }
501    }
502
503    /// Attempts to acquire this lock.
504    ///
505    /// If the lock could not be acquired at this time, then [`Err`] is returned.
506    /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
507    /// guard is dropped.
508    ///
509    /// This function does not block.
510    ///
511    /// # Errors
512    ///
513    /// If another user of this mutex panicked while holding the mutex, then
514    /// this call will return the [`Poisoned`] error if the mutex would
515    /// otherwise be acquired. An acquired lock guard will be contained
516    /// in the returned error.
517    ///
518    /// If the mutex could not be acquired because it is already locked, then
519    /// this call will return the [`WouldBlock`] error.
520    ///
521    /// [`Poisoned`]: TryLockError::Poisoned
522    /// [`WouldBlock`]: TryLockError::WouldBlock
523    ///
524    /// # Examples
525    ///
526    /// ```
527    /// use std::sync::{Arc, Mutex};
528    /// use std::thread;
529    ///
530    /// let mutex = Arc::new(Mutex::new(0));
531    /// let c_mutex = Arc::clone(&mutex);
532    ///
533    /// thread::spawn(move || {
534    ///     let mut lock = c_mutex.try_lock();
535    ///     if let Ok(ref mut mutex) = lock {
536    ///         **mutex = 10;
537    ///     } else {
538    ///         println!("try_lock failed");
539    ///     }
540    /// }).join().expect("`thread::spawn` should not fail");
541    /// assert_eq!(*mutex.lock().unwrap(), 10);
542    /// ```
543    #[stable(feature = "rust1", since = "1.0.0")]
544    #[rustc_should_not_be_called_on_const_items]
545    pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
546        unsafe {
547            if self.inner.try_lock() {
548                Ok(MutexGuard::new(self)?)
549            } else {
550                Err(TryLockError::WouldBlock)
551            }
552        }
553    }
554
555    /// Determines whether the mutex is poisoned.
556    ///
557    /// If another thread is active, the mutex can still become poisoned at any
558    /// time. You should not trust a `false` value for program correctness
559    /// without additional synchronization.
560    ///
561    /// # Examples
562    ///
563    /// ```
564    /// use std::sync::{Arc, Mutex};
565    /// use std::thread;
566    ///
567    /// let mutex = Arc::new(Mutex::new(0));
568    /// let c_mutex = Arc::clone(&mutex);
569    ///
570    /// let _ = thread::spawn(move || {
571    ///     let _lock = c_mutex.lock().unwrap();
572    ///     panic!(); // the mutex gets poisoned
573    /// }).join();
574    /// assert_eq!(mutex.is_poisoned(), true);
575    /// ```
576    #[inline]
577    #[stable(feature = "sync_poison", since = "1.2.0")]
578    pub fn is_poisoned(&self) -> bool {
579        self.poison.get()
580    }
581
582    /// Clear the poisoned state from a mutex.
583    ///
584    /// If the mutex is poisoned, it will remain poisoned until this function is called. This
585    /// allows recovering from a poisoned state and marking that it has recovered. For example, if
586    /// the value is overwritten by a known-good value, then the mutex can be marked as
587    /// un-poisoned. Or possibly, the value could be inspected to determine if it is in a
588    /// consistent state, and if so the poison is removed.
589    ///
590    /// # Examples
591    ///
592    /// ```
593    /// use std::sync::{Arc, Mutex};
594    /// use std::thread;
595    ///
596    /// let mutex = Arc::new(Mutex::new(0));
597    /// let c_mutex = Arc::clone(&mutex);
598    ///
599    /// let _ = thread::spawn(move || {
600    ///     let _lock = c_mutex.lock().unwrap();
601    ///     panic!(); // the mutex gets poisoned
602    /// }).join();
603    ///
604    /// assert_eq!(mutex.is_poisoned(), true);
605    /// let x = mutex.lock().unwrap_or_else(|mut e| {
606    ///     **e.get_mut() = 1;
607    ///     mutex.clear_poison();
608    ///     e.into_inner()
609    /// });
610    /// assert_eq!(mutex.is_poisoned(), false);
611    /// assert_eq!(*x, 1);
612    /// ```
613    #[inline]
614    #[stable(feature = "mutex_unpoison", since = "1.77.0")]
615    #[rustc_should_not_be_called_on_const_items]
616    pub fn clear_poison(&self) {
617        self.poison.clear();
618    }
619
620    /// Consumes this mutex, returning the underlying data.
621    ///
622    /// # Errors
623    ///
624    /// If another user of this mutex panicked while holding the mutex, then
625    /// this call will return an error containing the underlying data
626    /// instead.
627    ///
628    /// # Examples
629    ///
630    /// ```
631    /// use std::sync::Mutex;
632    ///
633    /// let mutex = Mutex::new(0);
634    /// assert_eq!(mutex.into_inner().unwrap(), 0);
635    /// ```
636    #[stable(feature = "mutex_into_inner", since = "1.6.0")]
637    pub fn into_inner(self) -> LockResult<T>
638    where
639        T: Sized,
640    {
641        let data = self.data.into_inner();
642        poison::map_result(self.poison.borrow(), |()| data)
643    }
644
645    /// Returns a mutable reference to the underlying data.
646    ///
647    /// Since this call borrows the `Mutex` mutably, no actual locking needs to
648    /// take place -- the mutable borrow statically guarantees no new locks can be acquired
649    /// while this reference exists. Note that this method does not clear any previous abandoned locks
650    /// (e.g., via [`forget()`] on a [`MutexGuard`]).
651    ///
652    /// # Errors
653    ///
654    /// If another user of this mutex panicked while holding the mutex, then
655    /// this call will return an error containing a mutable reference to the
656    /// underlying data instead.
657    ///
658    /// # Examples
659    ///
660    /// ```
661    /// use std::sync::Mutex;
662    ///
663    /// let mut mutex = Mutex::new(0);
664    /// *mutex.get_mut().unwrap() = 10;
665    /// assert_eq!(*mutex.lock().unwrap(), 10);
666    /// ```
667    ///
668    /// [`forget()`]: mem::forget
669    #[stable(feature = "mutex_get_mut", since = "1.6.0")]
670    pub fn get_mut(&mut self) -> LockResult<&mut T> {
671        let data = self.data.get_mut();
672        poison::map_result(self.poison.borrow(), |()| data)
673    }
674
675    /// Returns a raw pointer to the underlying data.
676    ///
677    /// The returned pointer is always non-null and properly aligned, but it is
678    /// the user's responsibility to ensure that any reads and writes through it
679    /// are properly synchronized to avoid data races, and that it is not read
680    /// or written through after the mutex is dropped.
681    #[unstable(feature = "mutex_data_ptr", issue = "140368")]
682    pub const fn data_ptr(&self) -> *mut T {
683        self.data.get()
684    }
685}
686
687#[stable(feature = "mutex_from", since = "1.24.0")]
688impl<T> From<T> for Mutex<T> {
689    /// Creates a new mutex in an unlocked state ready for use.
690    /// This is equivalent to [`Mutex::new`].
691    fn from(t: T) -> Self {
692        Mutex::new(t)
693    }
694}
695
696#[stable(feature = "mutex_default", since = "1.10.0")]
697impl<T: Default> Default for Mutex<T> {
698    /// Creates a `Mutex<T>`, with the `Default` value for T.
699    fn default() -> Mutex<T> {
700        Mutex::new(Default::default())
701    }
702}
703
704#[stable(feature = "rust1", since = "1.0.0")]
705impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
706    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
707        let mut d = f.debug_struct("Mutex");
708        match self.try_lock() {
709            Ok(guard) => {
710                d.field("data", &&*guard);
711            }
712            Err(TryLockError::Poisoned(err)) => {
713                d.field("data", &&**err.get_ref());
714            }
715            Err(TryLockError::WouldBlock) => {
716                d.field("data", &"<locked>");
717            }
718        }
719        d.field("poisoned", &self.poison.get());
720        d.finish_non_exhaustive()
721    }
722}
723
724impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
725    unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
726        poison::map_result(lock.poison.guard(), |guard| MutexGuard { lock, poison: guard })
727    }
728}
729
730#[stable(feature = "rust1", since = "1.0.0")]
731impl<T: ?Sized> Deref for MutexGuard<'_, T> {
732    type Target = T;
733
734    fn deref(&self) -> &T {
735        unsafe { &*self.lock.data.get() }
736    }
737}
738
739#[stable(feature = "rust1", since = "1.0.0")]
740impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
741    fn deref_mut(&mut self) -> &mut T {
742        unsafe { &mut *self.lock.data.get() }
743    }
744}
745
746#[stable(feature = "rust1", since = "1.0.0")]
747impl<T: ?Sized> Drop for MutexGuard<'_, T> {
748    #[inline]
749    fn drop(&mut self) {
750        unsafe {
751            self.lock.poison.done(&self.poison);
752            self.lock.inner.unlock();
753        }
754    }
755}
756
757#[stable(feature = "std_debug", since = "1.16.0")]
758impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
759    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760        fmt::Debug::fmt(&**self, f)
761    }
762}
763
764#[stable(feature = "std_guard_impls", since = "1.20.0")]
765impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
766    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
767        (**self).fmt(f)
768    }
769}
770
771/// For use in [`nonpoison::condvar`](super::condvar).
772pub(super) fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
773    &guard.lock.inner
774}
775
776/// For use in [`nonpoison::condvar`](super::condvar).
777pub(super) fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
778    &guard.lock.poison
779}
780
781impl<'a, T: ?Sized> MutexGuard<'a, T> {
782    /// Makes a [`MappedMutexGuard`] for a component of the borrowed data, e.g.
783    /// an enum variant.
784    ///
785    /// The `Mutex` is already locked, so this cannot fail.
786    ///
787    /// This is an associated function that needs to be used as
788    /// `MutexGuard::map(...)`. A method would interfere with methods of the
789    /// same name on the contents of the `MutexGuard` used through `Deref`.
790    #[unstable(feature = "mapped_lock_guards", issue = "117108")]
791    pub fn map<U, F>(orig: Self, f: F) -> MappedMutexGuard<'a, U>
792    where
793        F: FnOnce(&mut T) -> &mut U,
794        U: ?Sized,
795    {
796        // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard
797        // was created, and have been upheld throughout `map` and/or `filter_map`.
798        // The signature of the closure guarantees that it will not "leak" the lifetime of the reference
799        // passed to it. If the closure panics, the guard will be dropped.
800        let data = NonNull::from(f(unsafe { &mut *orig.lock.data.get() }));
801        let orig = ManuallyDrop::new(orig);
802        MappedMutexGuard {
803            data,
804            inner: &orig.lock.inner,
805            poison_flag: &orig.lock.poison,
806            poison: orig.poison.clone(),
807            _variance: PhantomData,
808        }
809    }
810
811    /// Makes a [`MappedMutexGuard`] for a component of the borrowed data. The
812    /// original guard is returned as an `Err(...)` if the closure returns
813    /// `None`.
814    ///
815    /// The `Mutex` is already locked, so this cannot fail.
816    ///
817    /// This is an associated function that needs to be used as
818    /// `MutexGuard::filter_map(...)`. A method would interfere with methods of the
819    /// same name on the contents of the `MutexGuard` used through `Deref`.
820    #[unstable(feature = "mapped_lock_guards", issue = "117108")]
821    pub fn filter_map<U, F>(orig: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
822    where
823        F: FnOnce(&mut T) -> Option<&mut U>,
824        U: ?Sized,
825    {
826        // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard
827        // was created, and have been upheld throughout `map` and/or `filter_map`.
828        // The signature of the closure guarantees that it will not "leak" the lifetime of the reference
829        // passed to it. If the closure panics, the guard will be dropped.
830        match f(unsafe { &mut *orig.lock.data.get() }) {
831            Some(data) => {
832                let data = NonNull::from(data);
833                let orig = ManuallyDrop::new(orig);
834                Ok(MappedMutexGuard {
835                    data,
836                    inner: &orig.lock.inner,
837                    poison_flag: &orig.lock.poison,
838                    poison: orig.poison.clone(),
839                    _variance: PhantomData,
840                })
841            }
842            None => Err(orig),
843        }
844    }
845}
846
847#[unstable(feature = "mapped_lock_guards", issue = "117108")]
848impl<T: ?Sized> Deref for MappedMutexGuard<'_, T> {
849    type Target = T;
850
851    fn deref(&self) -> &T {
852        unsafe { self.data.as_ref() }
853    }
854}
855
856#[unstable(feature = "mapped_lock_guards", issue = "117108")]
857impl<T: ?Sized> DerefMut for MappedMutexGuard<'_, T> {
858    fn deref_mut(&mut self) -> &mut T {
859        unsafe { self.data.as_mut() }
860    }
861}
862
863#[unstable(feature = "mapped_lock_guards", issue = "117108")]
864impl<T: ?Sized> Drop for MappedMutexGuard<'_, T> {
865    #[inline]
866    fn drop(&mut self) {
867        unsafe {
868            self.poison_flag.done(&self.poison);
869            self.inner.unlock();
870        }
871    }
872}
873
874#[unstable(feature = "mapped_lock_guards", issue = "117108")]
875impl<T: ?Sized + fmt::Debug> fmt::Debug for MappedMutexGuard<'_, T> {
876    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877        fmt::Debug::fmt(&**self, f)
878    }
879}
880
881#[unstable(feature = "mapped_lock_guards", issue = "117108")]
882impl<T: ?Sized + fmt::Display> fmt::Display for MappedMutexGuard<'_, T> {
883    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884        (**self).fmt(f)
885    }
886}
887
888impl<'a, T: ?Sized> MappedMutexGuard<'a, T> {
889    /// Makes a [`MappedMutexGuard`] for a component of the borrowed data, e.g.
890    /// an enum variant.
891    ///
892    /// The `Mutex` is already locked, so this cannot fail.
893    ///
894    /// This is an associated function that needs to be used as
895    /// `MappedMutexGuard::map(...)`. A method would interfere with methods of the
896    /// same name on the contents of the `MutexGuard` used through `Deref`.
897    #[unstable(feature = "mapped_lock_guards", issue = "117108")]
898    pub fn map<U, F>(mut orig: Self, f: F) -> MappedMutexGuard<'a, U>
899    where
900        F: FnOnce(&mut T) -> &mut U,
901        U: ?Sized,
902    {
903        // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard
904        // was created, and have been upheld throughout `map` and/or `filter_map`.
905        // The signature of the closure guarantees that it will not "leak" the lifetime of the reference
906        // passed to it. If the closure panics, the guard will be dropped.
907        let data = NonNull::from(f(unsafe { orig.data.as_mut() }));
908        let orig = ManuallyDrop::new(orig);
909        MappedMutexGuard {
910            data,
911            inner: orig.inner,
912            poison_flag: orig.poison_flag,
913            poison: orig.poison.clone(),
914            _variance: PhantomData,
915        }
916    }
917
918    /// Makes a [`MappedMutexGuard`] for a component of the borrowed data. The
919    /// original guard is returned as an `Err(...)` if the closure returns
920    /// `None`.
921    ///
922    /// The `Mutex` is already locked, so this cannot fail.
923    ///
924    /// This is an associated function that needs to be used as
925    /// `MappedMutexGuard::filter_map(...)`. A method would interfere with methods of the
926    /// same name on the contents of the `MutexGuard` used through `Deref`.
927    #[unstable(feature = "mapped_lock_guards", issue = "117108")]
928    pub fn filter_map<U, F>(mut orig: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
929    where
930        F: FnOnce(&mut T) -> Option<&mut U>,
931        U: ?Sized,
932    {
933        // SAFETY: the conditions of `MutexGuard::new` were satisfied when the original guard
934        // was created, and have been upheld throughout `map` and/or `filter_map`.
935        // The signature of the closure guarantees that it will not "leak" the lifetime of the reference
936        // passed to it. If the closure panics, the guard will be dropped.
937        match f(unsafe { orig.data.as_mut() }) {
938            Some(data) => {
939                let data = NonNull::from(data);
940                let orig = ManuallyDrop::new(orig);
941                Ok(MappedMutexGuard {
942                    data,
943                    inner: orig.inner,
944                    poison_flag: orig.poison_flag,
945                    poison: orig.poison.clone(),
946                    _variance: PhantomData,
947                })
948            }
949            None => Err(orig),
950        }
951    }
952}