]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mutex.rs
Fall out of the std::sync rewrite
[rust.git] / src / libstd / sync / mutex.rs
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.
4 //
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.
10
11 use prelude::*;
12
13 use cell::UnsafeCell;
14 use kinds::marker;
15 use sync::{poison, AsMutexGuard};
16 use sys_common::mutex as sys;
17
18 /// A mutual exclusion primitive useful for protecting shared data
19 ///
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.
26 ///
27 /// # Poisoning
28 ///
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.
33 ///
34 /// # Example
35 ///
36 /// ```rust
37 /// use std::sync::{Arc, Mutex};
38 /// const N: uint = 10;
39 ///
40 /// // Spawn a few threads to increment a shared variable (non-atomically), and
41 /// // let the main thread know once all increments are done.
42 /// //
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));
46 ///
47 /// let (tx, rx) = channel();
48 /// for _ in range(0u, 10) {
49 ///     let (data, tx) = (data.clone(), tx.clone());
50 ///     spawn(proc() {
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();
55 ///         *data += 1;
56 ///         if *data == N {
57 ///             tx.send(());
58 ///         }
59 ///         // the lock is unlocked here when `data` goes out of scope.
60 ///     });
61 /// }
62 ///
63 /// rx.recv();
64 /// ```
65 pub struct Mutex<T> {
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>,
72     data: UnsafeCell<T>,
73 }
74
75 /// The static mutex type is provided to allow for static allocation of mutexes.
76 ///
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.
82 ///
83 /// # Example
84 ///
85 /// ```rust
86 /// use std::sync::{StaticMutex, MUTEX_INIT};
87 ///
88 /// static LOCK: StaticMutex = MUTEX_INIT;
89 ///
90 /// {
91 ///     let _g = LOCK.lock();
92 ///     // do some productive work
93 /// }
94 /// // lock is unlocked here.
95 /// ```
96 pub struct StaticMutex {
97     lock: sys::Mutex,
98     poison: UnsafeCell<poison::Flag>,
99 }
100
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.
103 ///
104 /// The data protected by the mutex can be access through this guard via its
105 /// Deref and DerefMut implementations
106 #[must_use]
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,
112 }
113
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.
116 #[must_use]
117 pub struct StaticMutexGuard {
118     lock: &'static sys::Mutex,
119     marker: marker::NoSend,
120     poison: poison::Guard<'static>,
121 }
122
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 } },
128 };
129
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> {
133         Mutex {
134             inner: box MUTEX_INIT,
135             data: UnsafeCell::new(t),
136         }
137     }
138
139     /// Acquires a mutex, blocking the current task until it is able to do so.
140     ///
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.
145     ///
146     /// # Panics
147     ///
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> {
151         unsafe {
152             let lock: &'static StaticMutex = &*(&*self.inner as *const _);
153             MutexGuard::new(self, lock.lock())
154         }
155     }
156
157     /// Attempts to acquire this lock.
158     ///
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.
162     ///
163     /// This function does not block.
164     ///
165     /// # Panics
166     ///
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
169     /// acquired.
170     pub fn try_lock(&self) -> Option<MutexGuard<T>> {
171         unsafe {
172             let lock: &'static StaticMutex = &*(&*self.inner as *const _);
173             lock.try_lock().map(|guard| {
174                 MutexGuard::new(self, guard)
175             })
176         }
177     }
178 }
179
180 #[unsafe_destructor]
181 impl<T: Send> Drop for Mutex<T> {
182     fn drop(&mut self) {
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() }
187     }
188 }
189
190 impl StaticMutex {
191     /// Acquires this lock, see `Mutex::lock`
192     pub fn lock(&'static self) -> StaticMutexGuard {
193         unsafe { self.lock.lock() }
194         StaticMutexGuard::new(self)
195     }
196
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))
201         } else {
202             None
203         }
204     }
205
206     /// Deallocates resources associated with this static mutex.
207     ///
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.
211     ///
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) {
217         self.lock.destroy()
218     }
219 }
220
221 impl<'mutex, T> MutexGuard<'mutex, T> {
222     fn new(lock: &Mutex<T>, guard: StaticMutexGuard) -> MutexGuard<T> {
223         MutexGuard { __lock: lock, __guard: guard }
224     }
225 }
226
227 impl<'mutex, T> AsMutexGuard for MutexGuard<'mutex, T> {
228     unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { &self.__guard }
229 }
230
231 impl<'mutex, T> Deref<T> for MutexGuard<'mutex, T> {
232     fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__lock.data.get() } }
233 }
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() }
237     }
238 }
239
240 impl StaticMutexGuard {
241     fn new(lock: &'static StaticMutex) -> StaticMutexGuard {
242         unsafe {
243             let guard = StaticMutexGuard {
244                 lock: &lock.lock,
245                 marker: marker::NoSend,
246                 poison: (*lock.poison.get()).borrow(),
247             };
248             guard.poison.check("mutex");
249             return guard;
250         }
251     }
252 }
253
254 pub fn guard_lock(guard: &StaticMutexGuard) -> &sys::Mutex { guard.lock }
255 pub fn guard_poison(guard: &StaticMutexGuard) -> &poison::Guard {
256     &guard.poison
257 }
258
259 impl AsMutexGuard for StaticMutexGuard {
260     unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { self }
261 }
262
263 #[unsafe_destructor]
264 impl Drop for StaticMutexGuard {
265     fn drop(&mut self) {
266         unsafe {
267             self.poison.done();
268             self.lock.unlock();
269         }
270     }
271 }
272
273 #[cfg(test)]
274 mod test {
275     use prelude::*;
276
277     use task;
278     use sync::{Arc, Mutex, StaticMutex, MUTEX_INIT, Condvar};
279
280     #[test]
281     fn smoke() {
282         let m = Mutex::new(());
283         drop(m.lock());
284         drop(m.lock());
285     }
286
287     #[test]
288     fn smoke_static() {
289         static M: StaticMutex = MUTEX_INIT;
290         unsafe {
291             drop(M.lock());
292             drop(M.lock());
293             M.destroy();
294         }
295     }
296
297     #[test]
298     fn lots_and_lots() {
299         static M: StaticMutex = MUTEX_INIT;
300         static mut CNT: uint = 0;
301         static J: uint = 1000;
302         static K: uint = 3;
303
304         fn inc() {
305             for _ in range(0, J) {
306                 unsafe {
307                     let _g = M.lock();
308                     CNT += 1;
309                 }
310             }
311         }
312
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(()); });
319         }
320
321         drop(tx);
322         for _ in range(0, 2 * K) {
323             rx.recv();
324         }
325         assert_eq!(unsafe {CNT}, J * K * 2);
326         unsafe {
327             M.destroy();
328         }
329     }
330
331     #[test]
332     fn try_lock() {
333         let m = Mutex::new(());
334         assert!(m.try_lock().is_some());
335     }
336
337     #[test]
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();
342         spawn(proc() {
343             // wait until parent gets in
344             rx.recv();
345             let &(ref lock, ref cvar) = &*arc2;
346             let mut lock = lock.lock();
347             *lock = true;
348             cvar.notify_one();
349         });
350
351         let &(ref lock, ref cvar) = &*arc;
352         let lock = lock.lock();
353         tx.send(());
354         assert!(!*lock);
355         while !*lock {
356             cvar.wait(&lock);
357         }
358     }
359
360     #[test]
361     #[should_fail]
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();
366
367         spawn(proc() {
368             rx.recv();
369             let &(ref lock, ref cvar) = &*arc2;
370             let _g = lock.lock();
371             cvar.notify_one();
372             // Parent should fail when it wakes up.
373             panic!();
374         });
375
376         let &(ref lock, ref cvar) = &*arc;
377         let lock = lock.lock();
378         tx.send(());
379         while *lock == 1 {
380             cvar.wait(&lock);
381         }
382     }
383
384     #[test]
385     #[should_fail]
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);
392         });
393         let lock = arc.lock();
394         assert_eq!(*lock, 1);
395     }
396
397     #[test]
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();
404         spawn(proc() {
405             let lock = arc2.lock();
406             let lock2 = lock.deref().lock();
407             assert_eq!(*lock2, 1);
408             tx.send(());
409         });
410         rx.recv();
411     }
412
413     #[test]
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() {
418             struct Unwinder {
419                 i: Arc<Mutex<int>>,
420             }
421             impl Drop for Unwinder {
422                 fn drop(&mut self) {
423                     *self.i.lock() += 1;
424                 }
425             }
426             let _u = Unwinder { i: arc2 };
427             panic!();
428         });
429         let lock = arc.lock();
430         assert_eq!(*lock, 2);
431     }
432 }