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 sync::{poison, AsMutexGuard};
16 use sys_common::mutex as sys;
18 /// A mutual exclusion primitive useful for protecting shared data
20 /// This mutex will block threads waiting for the lock to become available. The
21 /// mutex can also be statically initialized or created via a `new`
22 /// constructor. Each mutex has a type parameter which represents the data that
23 /// it is protecting. The data can only be accessed through the RAII guards
24 /// returned from `lock` and `try_lock`, which guarantees that the data is only
25 /// ever accessed when the mutex is locked.
29 /// In order to prevent access to otherwise invalid data, each mutex will
30 /// propagate any panics which occur while the lock is held. Once a thread has
31 /// panicked while holding the lock, then all other threads will immediately
32 /// panic as well once they hold the lock.
37 /// use std::sync::{Arc, Mutex};
38 /// const N: uint = 10;
40 /// // Spawn a few threads to increment a shared variable (non-atomically), and
41 /// // let the main thread know once all increments are done.
43 /// // Here we're using an Arc to share memory among tasks, and the data inside
44 /// // the Arc is protected with a mutex.
45 /// let data = Arc::new(Mutex::new(0));
47 /// let (tx, rx) = channel();
48 /// for _ in range(0u, 10) {
49 /// let (data, tx) = (data.clone(), tx.clone());
51 /// // The shared static can only be accessed once the lock is held.
52 /// // Our non-atomic increment is safe because we're the only thread
53 /// // which can access the shared state when the lock is held.
54 /// let mut data = data.lock();
59 /// // the lock is unlocked here when `data` goes out of scope.
66 // Note that this static mutex is in a *box*, not inlined into the struct
67 // itself. Once a native mutex has been used once, its address can never
68 // change (it can't be moved). This mutex type can be safely moved at any
69 // time, so to ensure that the native mutex is used correctly we box the
70 // inner lock to give it a constant address.
71 inner: Box<StaticMutex>,
75 /// The static mutex type is provided to allow for static allocation of mutexes.
77 /// Note that this is a separate type because using a Mutex correctly means that
78 /// it needs to have a destructor run. In Rust, statics are not allowed to have
79 /// destructors. As a result, a `StaticMutex` has one extra method when compared
80 /// to a `Mutex`, a `destroy` method. This method is unsafe to call, and
81 /// documentation can be found directly on the method.
86 /// use std::sync::{StaticMutex, MUTEX_INIT};
88 /// static LOCK: StaticMutex = MUTEX_INIT;
91 /// let _g = LOCK.lock();
92 /// // do some productive work
94 /// // lock is unlocked here.
96 pub struct StaticMutex {
98 poison: UnsafeCell<poison::Flag>,
101 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
102 /// dropped (falls out of scope), the lock will be unlocked.
104 /// The data protected by the mutex can be access through this guard via its
105 /// Deref and DerefMut implementations
107 pub struct MutexGuard<'a, T: 'a> {
108 // funny underscores due to how Deref/DerefMut currently work (they
109 // disregard field privacy).
110 __lock: &'a Mutex<T>,
111 __guard: StaticMutexGuard,
114 /// An RAII implementation of a "scoped lock" of a static mutex. When this
115 /// structure is dropped (falls out of scope), the lock will be unlocked.
117 pub struct StaticMutexGuard {
118 lock: &'static sys::Mutex,
119 marker: marker::NoSend,
120 poison: poison::Guard<'static>,
123 /// Static initialization of a mutex. This constant can be used to initialize
124 /// other mutex constants.
125 pub const MUTEX_INIT: StaticMutex = StaticMutex {
126 lock: sys::MUTEX_INIT,
127 poison: UnsafeCell { value: poison::Flag { failed: false } },
130 impl<T: Send> Mutex<T> {
131 /// Creates a new mutex in an unlocked state ready for use.
132 pub fn new(t: T) -> Mutex<T> {
134 inner: box MUTEX_INIT,
135 data: UnsafeCell::new(t),
139 /// Acquires a mutex, blocking the current task until it is able to do so.
141 /// This function will block the local task until it is available to acquire
142 /// the mutex. Upon returning, the task is the only task with the mutex
143 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
144 /// the guard goes out of scope, the mutex will be unlocked.
148 /// If another user of this mutex panicked while holding the mutex, then
149 /// this call will immediately panic once the mutex is acquired.
150 pub fn lock(&self) -> MutexGuard<T> {
152 let lock: &'static StaticMutex = &*(&*self.inner as *const _);
153 MutexGuard::new(self, lock.lock())
157 /// Attempts to acquire this lock.
159 /// If the lock could not be acquired at this time, then `None` is returned.
160 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
161 /// guard is dropped.
163 /// This function does not block.
167 /// If another user of this mutex panicked while holding the mutex, then
168 /// this call will immediately panic if the mutex would otherwise be
170 pub fn try_lock(&self) -> Option<MutexGuard<T>> {
172 let lock: &'static StaticMutex = &*(&*self.inner as *const _);
173 lock.try_lock().map(|guard| {
174 MutexGuard::new(self, guard)
181 impl<T: Send> Drop for Mutex<T> {
183 // This is actually safe b/c we know that there is no further usage of
184 // this mutex (it's up to the user to arrange for a mutex to get
185 // dropped, that's not our job)
186 unsafe { self.inner.lock.destroy() }
191 /// Acquires this lock, see `Mutex::lock`
192 pub fn lock(&'static self) -> StaticMutexGuard {
193 unsafe { self.lock.lock() }
194 StaticMutexGuard::new(self)
197 /// Attempts to grab this lock, see `Mutex::try_lock`
198 pub fn try_lock(&'static self) -> Option<StaticMutexGuard> {
199 if unsafe { self.lock.try_lock() } {
200 Some(StaticMutexGuard::new(self))
206 /// Deallocates resources associated with this static mutex.
208 /// This method is unsafe because it provides no guarantees that there are
209 /// no active users of this mutex, and safety is not guaranteed if there are
210 /// active users of this mutex.
212 /// This method is required to ensure that there are no memory leaks on
213 /// *all* platforms. It may be the case that some platforms do not leak
214 /// memory if this method is not called, but this is not guaranteed to be
215 /// true on all platforms.
216 pub unsafe fn destroy(&'static self) {
221 impl<'mutex, T> MutexGuard<'mutex, T> {
222 fn new(lock: &Mutex<T>, guard: StaticMutexGuard) -> MutexGuard<T> {
223 MutexGuard { __lock: lock, __guard: guard }
227 impl<'mutex, T> AsMutexGuard for MutexGuard<'mutex, T> {
228 unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { &self.__guard }
231 impl<'mutex, T> Deref<T> for MutexGuard<'mutex, T> {
232 fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__lock.data.get() } }
234 impl<'mutex, T> DerefMut<T> for MutexGuard<'mutex, T> {
235 fn deref_mut<'a>(&'a mut self) -> &'a mut T {
236 unsafe { &mut *self.__lock.data.get() }
240 impl StaticMutexGuard {
241 fn new(lock: &'static StaticMutex) -> StaticMutexGuard {
243 let guard = StaticMutexGuard {
245 marker: marker::NoSend,
246 poison: (*lock.poison.get()).borrow(),
248 guard.poison.check("mutex");
254 pub fn guard_lock(guard: &StaticMutexGuard) -> &sys::Mutex { guard.lock }
255 pub fn guard_poison(guard: &StaticMutexGuard) -> &poison::Guard {
259 impl AsMutexGuard for StaticMutexGuard {
260 unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { self }
264 impl Drop for StaticMutexGuard {
278 use sync::{Arc, Mutex, StaticMutex, MUTEX_INIT, Condvar};
282 let m = Mutex::new(());
289 static M: StaticMutex = MUTEX_INIT;
299 static M: StaticMutex = MUTEX_INIT;
300 static mut CNT: uint = 0;
301 static J: uint = 1000;
305 for _ in range(0, J) {
313 let (tx, rx) = channel();
314 for _ in range(0, K) {
315 let tx2 = tx.clone();
316 spawn(proc() { inc(); tx2.send(()); });
317 let tx2 = tx.clone();
318 spawn(proc() { inc(); tx2.send(()); });
322 for _ in range(0, 2 * K) {
325 assert_eq!(unsafe {CNT}, J * K * 2);
333 let m = Mutex::new(());
334 assert!(m.try_lock().is_some());
338 fn test_mutex_arc_condvar() {
339 let arc = Arc::new((Mutex::new(false), Condvar::new()));
340 let arc2 = arc.clone();
341 let (tx, rx) = channel();
343 // wait until parent gets in
345 let &(ref lock, ref cvar) = &*arc2;
346 let mut lock = lock.lock();
351 let &(ref lock, ref cvar) = &*arc;
352 let lock = lock.lock();
362 fn test_arc_condvar_poison() {
363 let arc = Arc::new((Mutex::new(1i), Condvar::new()));
364 let arc2 = arc.clone();
365 let (tx, rx) = channel();
369 let &(ref lock, ref cvar) = &*arc2;
370 let _g = lock.lock();
372 // Parent should fail when it wakes up.
376 let &(ref lock, ref cvar) = &*arc;
377 let lock = lock.lock();
386 fn test_mutex_arc_poison() {
387 let arc = Arc::new(Mutex::new(1i));
388 let arc2 = arc.clone();
389 let _ = task::try(proc() {
390 let lock = arc2.lock();
391 assert_eq!(*lock, 2);
393 let lock = arc.lock();
394 assert_eq!(*lock, 1);
398 fn test_mutex_arc_nested() {
399 // Tests nested mutexes and access
400 // to underlying data.
401 let arc = Arc::new(Mutex::new(1i));
402 let arc2 = Arc::new(Mutex::new(arc));
403 let (tx, rx) = channel();
405 let lock = arc2.lock();
406 let lock2 = lock.deref().lock();
407 assert_eq!(*lock2, 1);
414 fn test_mutex_arc_access_in_unwind() {
415 let arc = Arc::new(Mutex::new(1i));
416 let arc2 = arc.clone();
417 let _ = task::try::<()>(proc() {
421 impl Drop for Unwinder {
426 let _u = Unwinder { i: arc2 };
429 let lock = arc.lock();
430 assert_eq!(*lock, 2);