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.
16 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 /// lock. Once a mutex is poisoned, all other tasks 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 tasks, 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 static 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 /// // tasks 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 /// # #![feature(std_misc)]
89 /// use std::sync::{Arc, Mutex};
92 /// let lock = Arc::new(Mutex::new(0_u32));
93 /// let lock2 = lock.clone();
95 /// let _ = thread::spawn(move || -> () {
96 /// // This thread will acquire the mutex first, unwrapping the result of
97 /// // `lock` because the lock has not been poisoned.
98 /// let _lock = lock2.lock().unwrap();
100 /// // This panic while holding the lock (`_guard` is in scope) will poison
105 /// // The lock is poisoned by this point, but the returned result can be
106 /// // pattern matched on to return the underlying guard on both branches.
107 /// let mut guard = match lock.lock() {
108 /// Ok(guard) => guard,
109 /// Err(poisoned) => poisoned.into_inner(),
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct Mutex<T> {
116 // Note that this static mutex is in a *box*, not inlined into the struct
117 // itself. Once a native mutex has been used once, its address can never
118 // change (it can't be moved). This mutex type can be safely moved at any
119 // time, so to ensure that the native mutex is used correctly we box the
120 // inner lock to give it a constant address.
121 inner: Box<StaticMutex>,
125 // these are the only places where `T: Send` matters; all other
126 // functionality works fine on a single thread.
127 unsafe impl<T: Send> Send for Mutex<T> { }
129 unsafe impl<T: Send> Sync for Mutex<T> { }
131 /// The static mutex type is provided to allow for static allocation of mutexes.
133 /// Note that this is a separate type because using a Mutex correctly means that
134 /// it needs to have a destructor run. In Rust, statics are not allowed to have
135 /// destructors. As a result, a `StaticMutex` has one extra method when compared
136 /// to a `Mutex`, a `destroy` method. This method is unsafe to call, and
137 /// documentation can be found directly on the method.
142 /// # #![feature(std_misc)]
143 /// use std::sync::{StaticMutex, MUTEX_INIT};
145 /// static LOCK: StaticMutex = MUTEX_INIT;
148 /// let _g = LOCK.lock().unwrap();
149 /// // do some productive work
151 /// // lock is unlocked here.
153 #[unstable(feature = "std_misc",
154 reason = "may be merged with Mutex in the future")]
155 pub struct StaticMutex {
157 poison: poison::Flag,
160 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
161 /// dropped (falls out of scope), the lock will be unlocked.
163 /// The data protected by the mutex can be access through this guard via its
164 /// `Deref` and `DerefMut` implementations
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub struct MutexGuard<'a, T: 'a> {
168 // funny underscores due to how Deref/DerefMut currently work (they
169 // disregard field privacy).
170 __lock: &'a StaticMutex,
171 __data: &'a UnsafeCell<T>,
172 __poison: poison::Guard,
175 impl<'a, T> !marker::Send for MutexGuard<'a, T> {}
177 /// Static initialization of a mutex. This constant can be used to initialize
178 /// other mutex constants.
179 #[unstable(feature = "std_misc",
180 reason = "may be merged with Mutex in the future")]
181 pub const MUTEX_INIT: StaticMutex = StaticMutex {
182 lock: sys::MUTEX_INIT,
183 poison: poison::FLAG_INIT,
187 /// Creates a new mutex in an unlocked state ready for use.
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub fn new(t: T) -> Mutex<T> {
191 inner: box MUTEX_INIT,
192 data: UnsafeCell::new(t),
196 /// Acquires a mutex, blocking the current task until it is able to do so.
198 /// This function will block the local task until it is available to acquire
199 /// the mutex. Upon returning, the task is the only task with the mutex
200 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
201 /// the guard goes out of scope, the mutex will be unlocked.
205 /// If another user of this mutex panicked while holding the mutex, then
206 /// this call will return an error once the mutex is acquired.
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn lock(&self) -> LockResult<MutexGuard<T>> {
209 unsafe { self.inner.lock.lock() }
210 MutexGuard::new(&*self.inner, &self.data)
213 /// Attempts to acquire this lock.
215 /// If the lock could not be acquired at this time, then `Err` is returned.
216 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
217 /// guard is dropped.
219 /// This function does not block.
223 /// If another user of this mutex panicked while holding the mutex, then
224 /// this call will return failure if the mutex would otherwise be
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
228 if unsafe { self.inner.lock.try_lock() } {
229 Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
231 Err(TryLockError::WouldBlock)
235 /// Determines whether the lock is poisoned.
237 /// If another thread is active, the lock can still become poisoned at any
238 /// time. You should not trust a `false` value for program correctness
239 /// without additional synchronization.
241 #[unstable(feature = "std_misc")]
242 pub fn is_poisoned(&self) -> bool {
243 self.inner.poison.get()
248 #[stable(feature = "rust1", since = "1.0.0")]
249 impl<T> Drop for Mutex<T> {
251 // This is actually safe b/c we know that there is no further usage of
252 // this mutex (it's up to the user to arrange for a mutex to get
253 // dropped, that's not our job)
254 unsafe { self.inner.lock.destroy() }
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T: fmt::Debug + 'static> fmt::Debug for Mutex<T> {
260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
261 match self.try_lock() {
262 Ok(guard) => write!(f, "Mutex {{ data: {:?} }}", *guard),
263 Err(TryLockError::Poisoned(err)) => {
264 write!(f, "Mutex {{ data: Poisoned({:?}) }}", **err.get_ref())
266 Err(TryLockError::WouldBlock) => write!(f, "Mutex {{ <locked> }}")
271 struct Dummy(UnsafeCell<()>);
272 unsafe impl Sync for Dummy {}
273 static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
276 /// Acquires this lock, see `Mutex::lock`
278 #[unstable(feature = "std_misc",
279 reason = "may be merged with Mutex in the future")]
280 pub fn lock(&'static self) -> LockResult<MutexGuard<()>> {
281 unsafe { self.lock.lock() }
282 MutexGuard::new(self, &DUMMY.0)
285 /// Attempts to grab this lock, see `Mutex::try_lock`
287 #[unstable(feature = "std_misc",
288 reason = "may be merged with Mutex in the future")]
289 pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
290 if unsafe { self.lock.try_lock() } {
291 Ok(try!(MutexGuard::new(self, &DUMMY.0)))
293 Err(TryLockError::WouldBlock)
297 /// Deallocates resources associated with this static mutex.
299 /// This method is unsafe because it provides no guarantees that there are
300 /// no active users of this mutex, and safety is not guaranteed if there are
301 /// active users of this mutex.
303 /// This method is required to ensure that there are no memory leaks on
304 /// *all* platforms. It may be the case that some platforms do not leak
305 /// memory if this method is not called, but this is not guaranteed to be
306 /// true on all platforms.
307 #[unstable(feature = "std_misc",
308 reason = "may be merged with Mutex in the future")]
309 pub unsafe fn destroy(&'static self) {
314 impl<'mutex, T> MutexGuard<'mutex, T> {
316 fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>)
317 -> LockResult<MutexGuard<'mutex, T>> {
318 poison::map_result(lock.poison.borrow(), |guard| {
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl<'mutex, T> Deref for MutexGuard<'mutex, T> {
332 fn deref<'a>(&'a self) -> &'a T {
333 unsafe { &*self.__data.get() }
336 #[stable(feature = "rust1", since = "1.0.0")]
337 impl<'mutex, T> DerefMut for MutexGuard<'mutex, T> {
338 fn deref_mut<'a>(&'a mut self) -> &'a mut T {
339 unsafe { &mut *self.__data.get() }
344 #[stable(feature = "rust1", since = "1.0.0")]
345 impl<'a, T> Drop for MutexGuard<'a, T> {
349 self.__lock.poison.done(&self.__poison);
350 self.__lock.lock.unlock();
355 pub fn guard_lock<'a, T>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
359 pub fn guard_poison<'a, T>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
367 use sync::mpsc::channel;
368 use sync::{Arc, Mutex, StaticMutex, MUTEX_INIT, Condvar};
371 struct Packet<T: Send>(Arc<(Mutex<T>, Condvar)>);
373 unsafe impl<T: Send> Send for Packet<T> {}
374 unsafe impl<T> Sync for Packet<T> {}
378 let m = Mutex::new(());
379 drop(m.lock().unwrap());
380 drop(m.lock().unwrap());
385 static M: StaticMutex = MUTEX_INIT;
387 drop(M.lock().unwrap());
388 drop(M.lock().unwrap());
395 static M: StaticMutex = MUTEX_INIT;
396 static mut CNT: u32 = 0;
403 let _g = M.lock().unwrap();
409 let (tx, rx) = channel();
411 let tx2 = tx.clone();
412 thread::spawn(move|| { inc(); tx2.send(()).unwrap(); });
413 let tx2 = tx.clone();
414 thread::spawn(move|| { inc(); tx2.send(()).unwrap(); });
421 assert_eq!(unsafe {CNT}, J * K * 2);
429 let m = Mutex::new(());
430 *m.try_lock().unwrap() = ();
434 fn test_mutex_arc_condvar() {
435 let packet = Packet(Arc::new((Mutex::new(false), Condvar::new())));
436 let packet2 = Packet(packet.0.clone());
437 let (tx, rx) = channel();
438 let _t = thread::spawn(move|| {
439 // wait until parent gets in
441 let &(ref lock, ref cvar) = &*packet2.0;
442 let mut lock = lock.lock().unwrap();
447 let &(ref lock, ref cvar) = &*packet.0;
448 let mut lock = lock.lock().unwrap();
449 tx.send(()).unwrap();
452 lock = cvar.wait(lock).unwrap();
457 fn test_arc_condvar_poison() {
458 let packet = Packet(Arc::new((Mutex::new(1), Condvar::new())));
459 let packet2 = Packet(packet.0.clone());
460 let (tx, rx) = channel();
462 let _t = thread::spawn(move || -> () {
464 let &(ref lock, ref cvar) = &*packet2.0;
465 let _g = lock.lock().unwrap();
467 // Parent should fail when it wakes up.
471 let &(ref lock, ref cvar) = &*packet.0;
472 let mut lock = lock.lock().unwrap();
473 tx.send(()).unwrap();
475 match cvar.wait(lock) {
478 assert_eq!(*lock, 1);
486 fn test_mutex_arc_poison() {
487 let arc = Arc::new(Mutex::new(1));
488 assert!(!arc.is_poisoned());
489 let arc2 = arc.clone();
490 let _ = thread::spawn(move|| {
491 let lock = arc2.lock().unwrap();
492 assert_eq!(*lock, 2);
494 assert!(arc.lock().is_err());
495 assert!(arc.is_poisoned());
499 fn test_mutex_arc_nested() {
500 // Tests nested mutexes and access
501 // to underlying data.
502 let arc = Arc::new(Mutex::new(1));
503 let arc2 = Arc::new(Mutex::new(arc));
504 let (tx, rx) = channel();
505 let _t = thread::spawn(move|| {
506 let lock = arc2.lock().unwrap();
507 let lock2 = lock.lock().unwrap();
508 assert_eq!(*lock2, 1);
509 tx.send(()).unwrap();
515 fn test_mutex_arc_access_in_unwind() {
516 let arc = Arc::new(Mutex::new(1));
517 let arc2 = arc.clone();
518 let _ = thread::spawn(move|| -> () {
522 impl Drop for Unwinder {
524 *self.i.lock().unwrap() += 1;
527 let _u = Unwinder { i: arc2 };
530 let lock = arc.lock().unwrap();
531 assert_eq!(*lock, 2);