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
),
222 impl<T
: ?Sized
> Mutex
<T
> {
223 /// Acquires a mutex, blocking the current thread until it is able to do so.
225 /// This function will block the local thread until it is available to acquire
226 /// the mutex. Upon returning, the thread is the only thread with the lock
227 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
228 /// the guard goes out of scope, the mutex will be unlocked.
230 /// The exact behavior on locking a mutex in the thread which already holds
231 /// the lock is left unspecified. However, this function will not return on
232 /// the second call (it might panic or deadlock, for example).
236 /// If another user of this mutex panicked while holding the mutex, then
237 /// this call will return an error once the mutex is acquired.
241 /// This function might panic when called if the lock is already held by
242 /// the current thread.
247 /// use std::sync::{Arc, Mutex};
250 /// let mutex = Arc::new(Mutex::new(0));
251 /// let c_mutex = Arc::clone(&mutex);
253 /// thread::spawn(move || {
254 /// *c_mutex.lock().unwrap() = 10;
255 /// }).join().expect("thread::spawn failed");
256 /// assert_eq!(*mutex.lock().unwrap(), 10);
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn lock(&self) -> LockResult
<MutexGuard
<'_
, T
>> {
261 self.inner
.raw_lock();
262 MutexGuard
::new(self)
266 /// Attempts to acquire this lock.
268 /// If the lock could not be acquired at this time, then [`Err`] is returned.
269 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
270 /// guard is dropped.
272 /// This function does not block.
276 /// If another user of this mutex panicked while holding the mutex, then
277 /// this call will return the [`Poisoned`] error if the mutex would
278 /// otherwise be acquired.
280 /// If the mutex could not be acquired because it is already locked, then
281 /// this call will return the [`WouldBlock`] error.
283 /// [`Poisoned`]: TryLockError::Poisoned
284 /// [`WouldBlock`]: TryLockError::WouldBlock
289 /// use std::sync::{Arc, Mutex};
292 /// let mutex = Arc::new(Mutex::new(0));
293 /// let c_mutex = Arc::clone(&mutex);
295 /// thread::spawn(move || {
296 /// let mut lock = c_mutex.try_lock();
297 /// if let Ok(ref mut mutex) = lock {
300 /// println!("try_lock failed");
302 /// }).join().expect("thread::spawn failed");
303 /// assert_eq!(*mutex.lock().unwrap(), 10);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn try_lock(&self) -> TryLockResult
<MutexGuard
<'_
, T
>> {
308 if self.inner
.try_lock() {
309 Ok(MutexGuard
::new(self)?
)
311 Err(TryLockError
::WouldBlock
)
316 /// Immediately drops the guard, and consequently unlocks the mutex.
318 /// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
319 /// Alternately, the guard will be automatically dropped when it goes out of scope.
322 /// #![feature(mutex_unlock)]
324 /// use std::sync::Mutex;
325 /// let mutex = Mutex::new(0);
327 /// let mut guard = mutex.lock().unwrap();
329 /// Mutex::unlock(guard);
331 #[unstable(feature = "mutex_unlock", issue = "81872")]
332 pub fn unlock(guard
: MutexGuard
<'_
, T
>) {
336 /// Determines whether the mutex is poisoned.
338 /// If another thread is active, the mutex can still become poisoned at any
339 /// time. You should not trust a `false` value for program correctness
340 /// without additional synchronization.
345 /// use std::sync::{Arc, Mutex};
348 /// let mutex = Arc::new(Mutex::new(0));
349 /// let c_mutex = Arc::clone(&mutex);
351 /// let _ = thread::spawn(move || {
352 /// let _lock = c_mutex.lock().unwrap();
353 /// panic!(); // the mutex gets poisoned
355 /// assert_eq!(mutex.is_poisoned(), true);
358 #[stable(feature = "sync_poison", since = "1.2.0")]
359 pub fn is_poisoned(&self) -> bool
{
363 /// Consumes this mutex, returning the underlying data.
367 /// If another user of this mutex panicked while holding the mutex, then
368 /// this call will return an error instead.
373 /// use std::sync::Mutex;
375 /// let mutex = Mutex::new(0);
376 /// assert_eq!(mutex.into_inner().unwrap(), 0);
378 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
379 pub fn into_inner(self) -> LockResult
<T
>
383 let data
= self.data
.into_inner();
384 poison
::map_result(self.poison
.borrow(), |_
| data
)
387 /// Returns a mutable reference to the underlying data.
389 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
390 /// take place -- the mutable borrow statically guarantees no locks exist.
394 /// If another user of this mutex panicked while holding the mutex, then
395 /// this call will return an error instead.
400 /// use std::sync::Mutex;
402 /// let mut mutex = Mutex::new(0);
403 /// *mutex.get_mut().unwrap() = 10;
404 /// assert_eq!(*mutex.lock().unwrap(), 10);
406 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
407 pub fn get_mut(&mut self) -> LockResult
<&mut T
> {
408 let data
= self.data
.get_mut();
409 poison
::map_result(self.poison
.borrow(), |_
| data
)
413 #[stable(feature = "mutex_from", since = "1.24.0")]
414 impl<T
> From
<T
> for Mutex
<T
> {
415 /// Creates a new mutex in an unlocked state ready for use.
416 /// This is equivalent to [`Mutex::new`].
417 fn from(t
: T
) -> Self {
422 #[stable(feature = "mutex_default", since = "1.10.0")]
423 impl<T
: ?Sized
+ Default
> Default
for Mutex
<T
> {
424 /// Creates a `Mutex<T>`, with the `Default` value for T.
425 fn default() -> Mutex
<T
> {
426 Mutex
::new(Default
::default())
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Mutex
<T
> {
432 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
433 let mut d
= f
.debug_struct("Mutex");
434 match self.try_lock() {
436 d
.field("data", &&*guard
);
438 Err(TryLockError
::Poisoned(err
)) => {
439 d
.field("data", &&**err
.get_ref());
441 Err(TryLockError
::WouldBlock
) => {
442 struct LockedPlaceholder
;
443 impl fmt
::Debug
for LockedPlaceholder
{
444 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
445 f
.write_str("<locked>")
448 d
.field("data", &LockedPlaceholder
);
451 d
.field("poisoned", &self.poison
.get());
452 d
.finish_non_exhaustive()
456 impl<'mutex
, T
: ?Sized
> MutexGuard
<'mutex
, T
> {
457 unsafe fn new(lock
: &'mutex Mutex
<T
>) -> LockResult
<MutexGuard
<'mutex
, T
>> {
458 poison
::map_result(lock
.poison
.borrow(), |guard
| MutexGuard { lock, poison: guard }
)
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<T
: ?Sized
> Deref
for MutexGuard
<'_
, T
> {
466 fn deref(&self) -> &T
{
467 unsafe { &*self.lock.data.get() }
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl<T
: ?Sized
> DerefMut
for MutexGuard
<'_
, T
> {
473 fn deref_mut(&mut self) -> &mut T
{
474 unsafe { &mut *self.lock.data.get() }
478 #[stable(feature = "rust1", since = "1.0.0")]
479 impl<T
: ?Sized
> Drop
for MutexGuard
<'_
, T
> {
483 self.lock
.poison
.done(&self.poison
);
484 self.lock
.inner
.raw_unlock();
489 #[stable(feature = "std_debug", since = "1.16.0")]
490 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for MutexGuard
<'_
, T
> {
491 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
492 fmt
::Debug
::fmt(&**self, f
)
496 #[stable(feature = "std_guard_impls", since = "1.20.0")]
497 impl<T
: ?Sized
+ fmt
::Display
> fmt
::Display
for MutexGuard
<'_
, T
> {
498 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
503 pub fn guard_lock
<'a
, T
: ?Sized
>(guard
: &MutexGuard
<'a
, T
>) -> &'a sys
::MovableMutex
{
507 pub fn guard_poison
<'a
, T
: ?Sized
>(guard
: &MutexGuard
<'a
, T
>) -> &'a poison
::Flag
{