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_type")]
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 #[stable(feature = "rust1", since = "1.0.0")]
192 pub struct MutexGuard
<'a
, T
: ?Sized
+ 'a
> {
194 poison
: poison
::Guard
,
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<T
: ?Sized
> !Send
for MutexGuard
<'_
, T
> {}
199 #[stable(feature = "mutexguard", since = "1.19.0")]
200 unsafe impl<T
: ?Sized
+ Sync
> Sync
for MutexGuard
<'_
, T
> {}
203 /// Creates a new mutex in an unlocked state ready for use.
208 /// use std::sync::Mutex;
210 /// let mutex = Mutex::new(0);
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn new(t
: T
) -> Mutex
<T
> {
215 inner
: sys
::MovableMutex
::new(),
216 poison
: poison
::Flag
::new(),
217 data
: UnsafeCell
::new(t
),
221 /// Immediately drops the guard, and consequently unlocks the mutex.
223 /// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
224 /// Alternately, the guard will be automatically dropped when it goes out of scope.
227 /// #![feature(mutex_unlock)]
229 /// use std::sync::Mutex;
230 /// let mutex = Mutex::new(0);
232 /// let mut guard = mutex.lock().unwrap();
234 /// Mutex::unlock(guard);
236 #[unstable(feature = "mutex_unlock", issue = "81872")]
237 pub fn unlock(guard
: MutexGuard
<'_
, T
>) {
242 impl<T
: ?Sized
> Mutex
<T
> {
243 /// Acquires a mutex, blocking the current thread until it is able to do so.
245 /// This function will block the local thread until it is available to acquire
246 /// the mutex. Upon returning, the thread is the only thread with the lock
247 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
248 /// the guard goes out of scope, the mutex will be unlocked.
250 /// The exact behavior on locking a mutex in the thread which already holds
251 /// the lock is left unspecified. However, this function will not return on
252 /// the second call (it might panic or deadlock, for example).
256 /// If another user of this mutex panicked while holding the mutex, then
257 /// this call will return an error once the mutex is acquired.
261 /// This function might panic when called if the lock is already held by
262 /// the current thread.
267 /// use std::sync::{Arc, Mutex};
270 /// let mutex = Arc::new(Mutex::new(0));
271 /// let c_mutex = Arc::clone(&mutex);
273 /// thread::spawn(move || {
274 /// *c_mutex.lock().unwrap() = 10;
275 /// }).join().expect("thread::spawn failed");
276 /// assert_eq!(*mutex.lock().unwrap(), 10);
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn lock(&self) -> LockResult
<MutexGuard
<'_
, T
>> {
281 self.inner
.raw_lock();
282 MutexGuard
::new(self)
286 /// Attempts to acquire this lock.
288 /// If the lock could not be acquired at this time, then [`Err`] is returned.
289 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
290 /// guard is dropped.
292 /// This function does not block.
296 /// If another user of this mutex panicked while holding the mutex, then
297 /// this call will return an error if the mutex would otherwise be
303 /// use std::sync::{Arc, Mutex};
306 /// let mutex = Arc::new(Mutex::new(0));
307 /// let c_mutex = Arc::clone(&mutex);
309 /// thread::spawn(move || {
310 /// let mut lock = c_mutex.try_lock();
311 /// if let Ok(ref mut mutex) = lock {
314 /// println!("try_lock failed");
316 /// }).join().expect("thread::spawn failed");
317 /// assert_eq!(*mutex.lock().unwrap(), 10);
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn try_lock(&self) -> TryLockResult
<MutexGuard
<'_
, T
>> {
322 if self.inner
.try_lock() {
323 Ok(MutexGuard
::new(self)?
)
325 Err(TryLockError
::WouldBlock
)
330 /// Determines whether the mutex is poisoned.
332 /// If another thread is active, the mutex can still become poisoned at any
333 /// time. You should not trust a `false` value for program correctness
334 /// without additional synchronization.
339 /// use std::sync::{Arc, Mutex};
342 /// let mutex = Arc::new(Mutex::new(0));
343 /// let c_mutex = Arc::clone(&mutex);
345 /// let _ = thread::spawn(move || {
346 /// let _lock = c_mutex.lock().unwrap();
347 /// panic!(); // the mutex gets poisoned
349 /// assert_eq!(mutex.is_poisoned(), true);
352 #[stable(feature = "sync_poison", since = "1.2.0")]
353 pub fn is_poisoned(&self) -> bool
{
357 /// Consumes this mutex, returning the underlying data.
361 /// If another user of this mutex panicked while holding the mutex, then
362 /// this call will return an error instead.
367 /// use std::sync::Mutex;
369 /// let mutex = Mutex::new(0);
370 /// assert_eq!(mutex.into_inner().unwrap(), 0);
372 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
373 pub fn into_inner(self) -> LockResult
<T
>
377 let data
= self.data
.into_inner();
378 poison
::map_result(self.poison
.borrow(), |_
| data
)
381 /// Returns a mutable reference to the underlying data.
383 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
384 /// take place -- the mutable borrow statically guarantees no locks exist.
388 /// If another user of this mutex panicked while holding the mutex, then
389 /// this call will return an error instead.
394 /// use std::sync::Mutex;
396 /// let mut mutex = Mutex::new(0);
397 /// *mutex.get_mut().unwrap() = 10;
398 /// assert_eq!(*mutex.lock().unwrap(), 10);
400 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
401 pub fn get_mut(&mut self) -> LockResult
<&mut T
> {
402 let data
= self.data
.get_mut();
403 poison
::map_result(self.poison
.borrow(), |_
| data
)
407 #[stable(feature = "mutex_from", since = "1.24.0")]
408 impl<T
> From
<T
> for Mutex
<T
> {
409 /// Creates a new mutex in an unlocked state ready for use.
410 /// This is equivalent to [`Mutex::new`].
411 fn from(t
: T
) -> Self {
416 #[stable(feature = "mutex_default", since = "1.10.0")]
417 impl<T
: ?Sized
+ Default
> Default
for Mutex
<T
> {
418 /// Creates a `Mutex<T>`, with the `Default` value for T.
419 fn default() -> Mutex
<T
> {
420 Mutex
::new(Default
::default())
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Mutex
<T
> {
426 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
427 let mut d
= f
.debug_struct("Mutex");
428 match self.try_lock() {
430 d
.field("data", &&*guard
);
432 Err(TryLockError
::Poisoned(err
)) => {
433 d
.field("data", &&**err
.get_ref());
435 Err(TryLockError
::WouldBlock
) => {
436 struct LockedPlaceholder
;
437 impl fmt
::Debug
for LockedPlaceholder
{
438 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
439 f
.write_str("<locked>")
442 d
.field("data", &LockedPlaceholder
);
445 d
.field("poisoned", &self.poison
.get());
446 d
.finish_non_exhaustive()
450 impl<'mutex
, T
: ?Sized
> MutexGuard
<'mutex
, T
> {
451 unsafe fn new(lock
: &'mutex Mutex
<T
>) -> LockResult
<MutexGuard
<'mutex
, T
>> {
452 poison
::map_result(lock
.poison
.borrow(), |guard
| MutexGuard { lock, poison: guard }
)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<T
: ?Sized
> Deref
for MutexGuard
<'_
, T
> {
460 fn deref(&self) -> &T
{
461 unsafe { &*self.lock.data.get() }
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl<T
: ?Sized
> DerefMut
for MutexGuard
<'_
, T
> {
467 fn deref_mut(&mut self) -> &mut T
{
468 unsafe { &mut *self.lock.data.get() }
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl<T
: ?Sized
> Drop
for MutexGuard
<'_
, T
> {
477 self.lock
.poison
.done(&self.poison
);
478 self.lock
.inner
.raw_unlock();
483 #[stable(feature = "std_debug", since = "1.16.0")]
484 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for MutexGuard
<'_
, T
> {
485 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
486 fmt
::Debug
::fmt(&**self, f
)
490 #[stable(feature = "std_guard_impls", since = "1.20.0")]
491 impl<T
: ?Sized
+ fmt
::Display
> fmt
::Display
for MutexGuard
<'_
, T
> {
492 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
497 pub fn guard_lock
<'a
, T
: ?Sized
>(guard
: &MutexGuard
<'a
, T
>) -> &'a sys
::MovableMutex
{
501 pub fn guard_poison
<'a
, T
: ?Sized
>(guard
: &MutexGuard
<'a
, T
>) -> &'a poison
::Flag
{