1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use ops
::{Deref, DerefMut}
;
17 use sys_common
::mutex
as sys
;
18 use sys_common
::poison
::{self, TryLockError, TryLockResult, LockResult}
;
20 /// A mutual exclusion primitive useful for protecting shared data
22 /// This mutex will block threads waiting for the lock to become available. The
23 /// mutex can also be statically initialized or created via a `new`
24 /// constructor. Each mutex has a type parameter which represents the data that
25 /// it is protecting. The data can only be accessed through the RAII guards
26 /// returned from `lock` and `try_lock`, which guarantees that the data is only
27 /// ever accessed when the mutex is locked.
31 /// The mutexes in this module implement a strategy called "poisoning" where a
32 /// mutex is considered poisoned whenever a thread panics while holding the
33 /// mutex. Once a mutex is poisoned, all other threads are unable to access the
34 /// data by default as it is likely tainted (some invariant is not being
37 /// For a mutex, this means that the `lock` and `try_lock` methods return a
38 /// `Result` which indicates whether a mutex has been poisoned or not. Most
39 /// usage of a mutex will simply `unwrap()` these results, propagating panics
40 /// among threads to ensure that a possibly invalid invariant is not witnessed.
42 /// A poisoned mutex, however, does not prevent all access to the underlying
43 /// data. The `PoisonError` type has an `into_inner` method which will return
44 /// the guard that would have otherwise been returned on a successful lock. This
45 /// allows access to the data, despite the lock being poisoned.
50 /// use std::sync::{Arc, Mutex};
52 /// use std::sync::mpsc::channel;
54 /// const N: usize = 10;
56 /// // Spawn a few threads to increment a shared variable (non-atomically), and
57 /// // let the main thread know once all increments are done.
59 /// // Here we're using an Arc to share memory among threads, and the data inside
60 /// // the Arc is protected with a mutex.
61 /// let data = Arc::new(Mutex::new(0));
63 /// let (tx, rx) = channel();
65 /// let (data, tx) = (data.clone(), tx.clone());
66 /// thread::spawn(move || {
67 /// // The shared state can only be accessed once the lock is held.
68 /// // Our non-atomic increment is safe because we're the only thread
69 /// // which can access the shared state when the lock is held.
71 /// // We unwrap() the return value to assert that we are not expecting
72 /// // threads to ever fail while holding the lock.
73 /// let mut data = data.lock().unwrap();
76 /// tx.send(()).unwrap();
78 /// // the lock is unlocked here when `data` goes out of scope.
82 /// rx.recv().unwrap();
85 /// To recover from a poisoned mutex:
88 /// use std::sync::{Arc, Mutex};
91 /// let lock = Arc::new(Mutex::new(0_u32));
92 /// let lock2 = lock.clone();
94 /// let _ = thread::spawn(move || -> () {
95 /// // This thread will acquire the mutex first, unwrapping the result of
96 /// // `lock` because the lock has not been poisoned.
97 /// let _guard = lock2.lock().unwrap();
99 /// // This panic while holding the lock (`_guard` is in scope) will poison
104 /// // The lock is poisoned by this point, but the returned result can be
105 /// // pattern matched on to return the underlying guard on both branches.
106 /// let mut guard = match lock.lock() {
107 /// Ok(guard) => guard,
108 /// Err(poisoned) => poisoned.into_inner(),
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub struct Mutex
<T
: ?Sized
> {
115 // Note that this mutex is in a *box*, not inlined into the struct itself.
116 // Once a native mutex has been used once, its address can never change (it
117 // can't be moved). This mutex type can be safely moved at any time, so to
118 // ensure that the native mutex is used correctly we box the inner mutex to
119 // give it a constant address.
120 inner
: Box
<sys
::Mutex
>,
121 poison
: poison
::Flag
,
125 // these are the only places where `T: Send` matters; all other
126 // functionality works fine on a single thread.
127 #[stable(feature = "rust1", since = "1.0.0")]
128 unsafe impl<T
: ?Sized
+ Send
> Send
for Mutex
<T
> { }
129 #[stable(feature = "rust1", since = "1.0.0")]
130 unsafe impl<T
: ?Sized
+ Send
> Sync
for Mutex
<T
> { }
132 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
133 /// dropped (falls out of scope), the lock will be unlocked.
135 /// The data protected by the mutex can be accessed through this guard via its
136 /// [`Deref`] and [`DerefMut`] implementations.
138 /// This structure is created by the [`lock`] and [`try_lock`] methods on
141 /// [`Deref`]: ../../std/ops/trait.Deref.html
142 /// [`DerefMut`]: ../../std/ops/trait.DerefMut.html
143 /// [`lock`]: struct.Mutex.html#method.lock
144 /// [`try_lock`]: struct.Mutex.html#method.try_lock
145 /// [`Mutex`]: struct.Mutex.html
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct MutexGuard
<'a
, T
: ?Sized
+ 'a
> {
149 // funny underscores due to how Deref/DerefMut currently work (they
150 // disregard field privacy).
151 __lock
: &'a Mutex
<T
>,
152 __poison
: poison
::Guard
,
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<'a
, T
: ?Sized
> !marker
::Send
for MutexGuard
<'a
, T
> {}
159 /// Creates a new mutex in an unlocked state ready for use.
164 /// use std::sync::Mutex;
166 /// let mutex = Mutex::new(0);
168 #[stable(feature = "rust1", since = "1.0.0")]
169 pub fn new(t
: T
) -> Mutex
<T
> {
171 inner
: box sys
::Mutex
::new(),
172 poison
: poison
::Flag
::new(),
173 data
: UnsafeCell
::new(t
),
182 impl<T
: ?Sized
> Mutex
<T
> {
183 /// Acquires a mutex, blocking the current thread until it is able to do so.
185 /// This function will block the local thread until it is available to acquire
186 /// the mutex. Upon returning, the thread is the only thread with the lock
187 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
188 /// the guard goes out of scope, the mutex will be unlocked.
190 /// The exact behavior on locking a mutex in the thread which already holds
191 /// the lock is left unspecified. However, this function will not return on
192 /// the second call (it might panic or deadlock, for example).
196 /// If another user of this mutex panicked while holding the mutex, then
197 /// this call will return an error once the mutex is acquired.
201 /// This function might panic when called if the lock is already held by
202 /// the current thread.
207 /// use std::sync::{Arc, Mutex};
210 /// let mutex = Arc::new(Mutex::new(0));
211 /// let c_mutex = mutex.clone();
213 /// thread::spawn(move || {
214 /// *c_mutex.lock().unwrap() = 10;
215 /// }).join().expect("thread::spawn failed");
216 /// assert_eq!(*mutex.lock().unwrap(), 10);
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn lock(&self) -> LockResult
<MutexGuard
<T
>> {
222 MutexGuard
::new(self)
226 /// Attempts to acquire this lock.
228 /// If the lock could not be acquired at this time, then `Err` is returned.
229 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
230 /// guard is dropped.
232 /// This function does not block.
236 /// If another user of this mutex panicked while holding the mutex, then
237 /// this call will return failure if the mutex would otherwise be
243 /// use std::sync::{Arc, Mutex};
246 /// let mutex = Arc::new(Mutex::new(0));
247 /// let c_mutex = mutex.clone();
249 /// thread::spawn(move || {
250 /// let mut lock = c_mutex.try_lock();
251 /// if let Ok(ref mut mutex) = lock {
254 /// println!("try_lock failed");
256 /// }).join().expect("thread::spawn failed");
257 /// assert_eq!(*mutex.lock().unwrap(), 10);
259 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn try_lock(&self) -> TryLockResult
<MutexGuard
<T
>> {
262 if self.inner
.try_lock() {
263 Ok(MutexGuard
::new(self)?
)
265 Err(TryLockError
::WouldBlock
)
270 /// Determines whether the mutex is poisoned.
272 /// If another thread is active, the mutex can still become poisoned at any
273 /// time. You should not trust a `false` value for program correctness
274 /// without additional synchronization.
279 /// use std::sync::{Arc, Mutex};
282 /// let mutex = Arc::new(Mutex::new(0));
283 /// let c_mutex = mutex.clone();
285 /// let _ = thread::spawn(move || {
286 /// let _lock = c_mutex.lock().unwrap();
287 /// panic!(); // the mutex gets poisoned
289 /// assert_eq!(mutex.is_poisoned(), true);
292 #[stable(feature = "sync_poison", since = "1.2.0")]
293 pub fn is_poisoned(&self) -> bool
{
297 /// Consumes this mutex, returning the underlying data.
301 /// If another user of this mutex panicked while holding the mutex, then
302 /// this call will return an error instead.
307 /// use std::sync::Mutex;
309 /// let mutex = Mutex::new(0);
310 /// assert_eq!(mutex.into_inner().unwrap(), 0);
312 #[stable(feature = "mutex_into_inner", since = "1.6.0")]
313 pub fn into_inner(self) -> LockResult
<T
> where T
: Sized
{
314 // We know statically that there are no outstanding references to
315 // `self` so there's no need to lock the inner mutex.
317 // To get the inner value, we'd like to call `data.into_inner()`,
318 // but because `Mutex` impl-s `Drop`, we can't move out of it, so
319 // we'll have to destructure it manually instead.
321 // Like `let Mutex { inner, poison, data } = self`.
322 let (inner
, poison
, data
) = {
323 let Mutex { ref inner, ref poison, ref data }
= self;
324 (ptr
::read(inner
), ptr
::read(poison
), ptr
::read(data
))
327 inner
.destroy(); // Keep in sync with the `Drop` impl.
330 poison
::map_result(poison
.borrow(), |_
| data
.into_inner())
334 /// Returns a mutable reference to the underlying data.
336 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
337 /// take place---the mutable borrow statically guarantees no locks exist.
341 /// If another user of this mutex panicked while holding the mutex, then
342 /// this call will return an error instead.
347 /// use std::sync::Mutex;
349 /// let mut mutex = Mutex::new(0);
350 /// *mutex.get_mut().unwrap() = 10;
351 /// assert_eq!(*mutex.lock().unwrap(), 10);
353 #[stable(feature = "mutex_get_mut", since = "1.6.0")]
354 pub fn get_mut(&mut self) -> LockResult
<&mut T
> {
355 // We know statically that there are no other references to `self`, so
356 // there's no need to lock the inner mutex.
357 let data
= unsafe { &mut *self.data.get() }
;
358 poison
::map_result(self.poison
.borrow(), |_
| data
)
362 #[stable(feature = "rust1", since = "1.0.0")]
363 unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> {
365 // This is actually safe b/c we know that there is no further usage of
366 // this mutex (it's up to the user to arrange for a mutex to get
367 // dropped, that's not our job)
369 // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`.
370 unsafe { self.inner.destroy() }
374 #[stable(feature = "mutex_default", since = "1.9.0")]
375 impl<T
: ?Sized
+ Default
> Default
for Mutex
<T
> {
376 /// Creates a `Mutex<T>`, with the `Default` value for T.
377 fn default() -> Mutex
<T
> {
378 Mutex
::new(Default
::default())
382 #[stable(feature = "rust1", since = "1.0.0")]
383 impl<T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Mutex
<T
> {
384 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
385 match self.try_lock() {
386 Ok(guard
) => write
!(f
, "Mutex {{ data: {:?} }}", &*guard
),
387 Err(TryLockError
::Poisoned(err
)) => {
388 write
!(f
, "Mutex {{ data: Poisoned({:?}) }}", &**err
.get_ref())
390 Err(TryLockError
::WouldBlock
) => write
!(f
, "Mutex {{ <locked> }}")
395 impl<'mutex
, T
: ?Sized
> MutexGuard
<'mutex
, T
> {
396 unsafe fn new(lock
: &'mutex Mutex
<T
>) -> LockResult
<MutexGuard
<'mutex
, T
>> {
397 poison
::map_result(lock
.poison
.borrow(), |guard
| {
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<'mutex
, T
: ?Sized
> Deref
for MutexGuard
<'mutex
, T
> {
410 fn deref(&self) -> &T
{
411 unsafe { &*self.__lock.data.get() }
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl<'mutex
, T
: ?Sized
> DerefMut
for MutexGuard
<'mutex
, T
> {
417 fn deref_mut(&mut self) -> &mut T
{
418 unsafe { &mut *self.__lock.data.get() }
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<'a
, T
: ?Sized
> Drop
for MutexGuard
<'a
, T
> {
427 self.__lock
.poison
.done(&self.__poison
);
428 self.__lock
.inner
.unlock();
433 #[stable(feature = "std_debug", since = "1.16.0")]
434 impl<'a
, T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for MutexGuard
<'a
, T
> {
435 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
436 f
.debug_struct("MutexGuard")
437 .field("lock", &self.__lock
)
442 pub fn guard_lock
<'a
, T
: ?Sized
>(guard
: &MutexGuard
<'a
, T
>) -> &'a sys
::Mutex
{
446 pub fn guard_poison
<'a
, T
: ?Sized
>(guard
: &MutexGuard
<'a
, T
>) -> &'a poison
::Flag
{
450 #[cfg(all(test, not(target_os = "emscripten")))]
452 use sync
::mpsc
::channel
;
453 use sync
::{Arc, Mutex, Condvar}
;
454 use sync
::atomic
::{AtomicUsize, Ordering}
;
457 struct Packet
<T
>(Arc
<(Mutex
<T
>, Condvar
)>);
459 #[derive(Eq, PartialEq, Debug)]
462 unsafe impl<T
: Send
> Send
for Packet
<T
> {}
463 unsafe impl<T
> Sync
for Packet
<T
> {}
467 let m
= Mutex
::new(());
468 drop(m
.lock().unwrap());
469 drop(m
.lock().unwrap());
477 let m
= Arc
::new(Mutex
::new(0));
479 fn inc(m
: &Mutex
<u32>) {
481 *m
.lock().unwrap() += 1;
485 let (tx
, rx
) = channel();
487 let tx2
= tx
.clone();
489 thread
::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); }
);
490 let tx2
= tx
.clone();
492 thread
::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); }
);
499 assert_eq
!(*m
.lock().unwrap(), J
* K
* 2);
504 let m
= Mutex
::new(());
505 *m
.try_lock().unwrap() = ();
509 fn test_into_inner() {
510 let m
= Mutex
::new(NonCopy(10));
511 assert_eq
!(m
.into_inner().unwrap(), NonCopy(10));
515 fn test_into_inner_drop() {
516 struct Foo(Arc
<AtomicUsize
>);
519 self.0.fetch_add
(1, Ordering
::SeqCst
);
522 let num_drops
= Arc
::new(AtomicUsize
::new(0));
523 let m
= Mutex
::new(Foo(num_drops
.clone()));
524 assert_eq
!(num_drops
.load(Ordering
::SeqCst
), 0);
526 let _inner
= m
.into_inner().unwrap();
527 assert_eq
!(num_drops
.load(Ordering
::SeqCst
), 0);
529 assert_eq
!(num_drops
.load(Ordering
::SeqCst
), 1);
533 fn test_into_inner_poison() {
534 let m
= Arc
::new(Mutex
::new(NonCopy(10)));
536 let _
= thread
::spawn(move || {
537 let _lock
= m2
.lock().unwrap();
538 panic
!("test panic in inner thread to poison mutex");
541 assert
!(m
.is_poisoned());
542 match Arc
::try_unwrap(m
).unwrap().into_inner() {
543 Err(e
) => assert_eq
!(e
.into_inner(), NonCopy(10)),
544 Ok(x
) => panic
!("into_inner of poisoned Mutex is Ok: {:?}", x
),
550 let mut m
= Mutex
::new(NonCopy(10));
551 *m
.get_mut().unwrap() = NonCopy(20);
552 assert_eq
!(m
.into_inner().unwrap(), NonCopy(20));
556 fn test_get_mut_poison() {
557 let m
= Arc
::new(Mutex
::new(NonCopy(10)));
559 let _
= thread
::spawn(move || {
560 let _lock
= m2
.lock().unwrap();
561 panic
!("test panic in inner thread to poison mutex");
564 assert
!(m
.is_poisoned());
565 match Arc
::try_unwrap(m
).unwrap().get_mut() {
566 Err(e
) => assert_eq
!(*e
.into_inner(), NonCopy(10)),
567 Ok(x
) => panic
!("get_mut of poisoned Mutex is Ok: {:?}", x
),
572 fn test_mutex_arc_condvar() {
573 let packet
= Packet(Arc
::new((Mutex
::new(false), Condvar
::new())));
574 let packet2
= Packet(packet
.0.clone());
575 let (tx
, rx
) = channel();
576 let _t
= thread
::spawn(move|| {
577 // wait until parent gets in
579 let &(ref lock
, ref cvar
) = &*packet2
.0
;
580 let mut lock
= lock
.lock().unwrap();
585 let &(ref lock
, ref cvar
) = &*packet
.0;
586 let mut lock
= lock
.lock().unwrap();
587 tx
.send(()).unwrap();
590 lock
= cvar
.wait(lock
).unwrap();
595 fn test_arc_condvar_poison() {
596 let packet
= Packet(Arc
::new((Mutex
::new(1), Condvar
::new())));
597 let packet2
= Packet(packet
.0.clone());
598 let (tx
, rx
) = channel();
600 let _t
= thread
::spawn(move || -> () {
602 let &(ref lock
, ref cvar
) = &*packet2
.0
;
603 let _g
= lock
.lock().unwrap();
605 // Parent should fail when it wakes up.
609 let &(ref lock
, ref cvar
) = &*packet
.0;
610 let mut lock
= lock
.lock().unwrap();
611 tx
.send(()).unwrap();
613 match cvar
.wait(lock
) {
616 assert_eq
!(*lock
, 1);
624 fn test_mutex_arc_poison() {
625 let arc
= Arc
::new(Mutex
::new(1));
626 assert
!(!arc
.is_poisoned());
627 let arc2
= arc
.clone();
628 let _
= thread
::spawn(move|| {
629 let lock
= arc2
.lock().unwrap();
630 assert_eq
!(*lock
, 2);
632 assert
!(arc
.lock().is_err());
633 assert
!(arc
.is_poisoned());
637 fn test_mutex_arc_nested() {
638 // Tests nested mutexes and access
639 // to underlying data.
640 let arc
= Arc
::new(Mutex
::new(1));
641 let arc2
= Arc
::new(Mutex
::new(arc
));
642 let (tx
, rx
) = channel();
643 let _t
= thread
::spawn(move|| {
644 let lock
= arc2
.lock().unwrap();
645 let lock2
= lock
.lock().unwrap();
646 assert_eq
!(*lock2
, 1);
647 tx
.send(()).unwrap();
653 fn test_mutex_arc_access_in_unwind() {
654 let arc
= Arc
::new(Mutex
::new(1));
655 let arc2
= arc
.clone();
656 let _
= thread
::spawn(move|| -> () {
660 impl Drop
for Unwinder
{
662 *self.i
.lock().unwrap() += 1;
665 let _u
= Unwinder { i: arc2 }
;
668 let lock
= arc
.lock().unwrap();
669 assert_eq
!(*lock
, 2);
673 fn test_mutex_unsized() {
674 let mutex
: &Mutex
<[i32]> = &Mutex
::new([1, 2, 3]);
676 let b
= &mut *mutex
.lock().unwrap();
680 let comp
: &[i32] = &[4, 2, 5];
681 assert_eq
!(&*mutex
.lock().unwrap(), comp
);