]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mutex.rs
Auto merge of #24865 - bluss:range-size, r=alexcrichton
[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::v1::*;
12
13 use cell::UnsafeCell;
14 use fmt;
15 use marker;
16 use ops::{Deref, DerefMut};
17 use sys_common::mutex as sys;
18 use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
19
20 /// A mutual exclusion primitive useful for protecting shared data
21 ///
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.
28 ///
29 /// # Poisoning
30 ///
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
35 /// upheld).
36 ///
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.
41 ///
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.
46 ///
47 /// # Examples
48 ///
49 /// ```
50 /// use std::sync::{Arc, Mutex};
51 /// use std::thread;
52 /// use std::sync::mpsc::channel;
53 ///
54 /// const N: usize = 10;
55 ///
56 /// // Spawn a few threads to increment a shared variable (non-atomically), and
57 /// // let the main thread know once all increments are done.
58 /// //
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));
62 ///
63 /// let (tx, rx) = channel();
64 /// for _ in 0..10 {
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.
70 ///         //
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();
74 ///         *data += 1;
75 ///         if *data == N {
76 ///             tx.send(()).unwrap();
77 ///         }
78 ///         // the lock is unlocked here when `data` goes out of scope.
79 ///     });
80 /// }
81 ///
82 /// rx.recv().unwrap();
83 /// ```
84 ///
85 /// To recover from a poisoned mutex:
86 ///
87 /// ```
88 /// # #![feature(std_misc)]
89 /// use std::sync::{Arc, Mutex};
90 /// use std::thread;
91 ///
92 /// let lock = Arc::new(Mutex::new(0_u32));
93 /// let lock2 = lock.clone();
94 ///
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();
99 ///
100 ///     // This panic while holding the lock (`_guard` is in scope) will poison
101 ///     // the mutex.
102 ///     panic!();
103 /// }).join();
104 ///
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(),
110 /// };
111 ///
112 /// *guard += 1;
113 /// ```
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>,
122     data: UnsafeCell<T>,
123 }
124
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> { }
128
129 unsafe impl<T: Send> Sync for Mutex<T> { }
130
131 /// The static mutex type is provided to allow for static allocation of mutexes.
132 ///
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.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// # #![feature(std_misc)]
143 /// use std::sync::{StaticMutex, MUTEX_INIT};
144 ///
145 /// static LOCK: StaticMutex = MUTEX_INIT;
146 ///
147 /// {
148 ///     let _g = LOCK.lock().unwrap();
149 ///     // do some productive work
150 /// }
151 /// // lock is unlocked here.
152 /// ```
153 #[unstable(feature = "std_misc",
154            reason = "may be merged with Mutex in the future")]
155 pub struct StaticMutex {
156     lock: sys::Mutex,
157     poison: poison::Flag,
158 }
159
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.
162 ///
163 /// The data protected by the mutex can be access through this guard via its
164 /// `Deref` and `DerefMut` implementations
165 #[must_use]
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,
173 }
174
175 impl<'a, T> !marker::Send for MutexGuard<'a, T> {}
176
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,
184 };
185
186 impl<T> Mutex<T> {
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> {
190         Mutex {
191             inner: box MUTEX_INIT,
192             data: UnsafeCell::new(t),
193         }
194     }
195
196     /// Acquires a mutex, blocking the current task until it is able to do so.
197     ///
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.
202     ///
203     /// # Failure
204     ///
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)
211     }
212
213     /// Attempts to acquire this lock.
214     ///
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.
218     ///
219     /// This function does not block.
220     ///
221     /// # Failure
222     ///
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
225     /// acquired.
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)))
230         } else {
231             Err(TryLockError::WouldBlock)
232         }
233     }
234
235     /// Determines whether the lock is poisoned.
236     ///
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.
240     #[inline]
241     #[unstable(feature = "std_misc")]
242     pub fn is_poisoned(&self) -> bool {
243         self.inner.poison.get()
244     }
245 }
246
247 #[unsafe_destructor]
248 #[stable(feature = "rust1", since = "1.0.0")]
249 impl<T> Drop for Mutex<T> {
250     fn drop(&mut self) {
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() }
255     }
256 }
257
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())
265             },
266             Err(TryLockError::WouldBlock) => write!(f, "Mutex {{ <locked> }}")
267         }
268     }
269 }
270
271 struct Dummy(UnsafeCell<()>);
272 unsafe impl Sync for Dummy {}
273 static DUMMY: Dummy = Dummy(UnsafeCell { value: () });
274
275 impl StaticMutex {
276     /// Acquires this lock, see `Mutex::lock`
277     #[inline]
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)
283     }
284
285     /// Attempts to grab this lock, see `Mutex::try_lock`
286     #[inline]
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)))
292         } else {
293             Err(TryLockError::WouldBlock)
294         }
295     }
296
297     /// Deallocates resources associated with this static mutex.
298     ///
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.
302     ///
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) {
310         self.lock.destroy()
311     }
312 }
313
314 impl<'mutex, T> MutexGuard<'mutex, T> {
315
316     fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>)
317            -> LockResult<MutexGuard<'mutex, T>> {
318         poison::map_result(lock.poison.borrow(), |guard| {
319             MutexGuard {
320                 __lock: lock,
321                 __data: data,
322                 __poison: guard,
323             }
324         })
325     }
326 }
327
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl<'mutex, T> Deref for MutexGuard<'mutex, T> {
330     type Target = T;
331
332     fn deref<'a>(&'a self) -> &'a T {
333         unsafe { &*self.__data.get() }
334     }
335 }
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() }
340     }
341 }
342
343 #[unsafe_destructor]
344 #[stable(feature = "rust1", since = "1.0.0")]
345 impl<'a, T> Drop for MutexGuard<'a, T> {
346     #[inline]
347     fn drop(&mut self) {
348         unsafe {
349             self.__lock.poison.done(&self.__poison);
350             self.__lock.lock.unlock();
351         }
352     }
353 }
354
355 pub fn guard_lock<'a, T>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
356     &guard.__lock.lock
357 }
358
359 pub fn guard_poison<'a, T>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
360     &guard.__lock.poison
361 }
362
363 #[cfg(test)]
364 mod tests {
365     use prelude::v1::*;
366
367     use sync::mpsc::channel;
368     use sync::{Arc, Mutex, StaticMutex, MUTEX_INIT, Condvar};
369     use thread;
370
371     struct Packet<T: Send>(Arc<(Mutex<T>, Condvar)>);
372
373     unsafe impl<T: Send> Send for Packet<T> {}
374     unsafe impl<T> Sync for Packet<T> {}
375
376     #[test]
377     fn smoke() {
378         let m = Mutex::new(());
379         drop(m.lock().unwrap());
380         drop(m.lock().unwrap());
381     }
382
383     #[test]
384     fn smoke_static() {
385         static M: StaticMutex = MUTEX_INIT;
386         unsafe {
387             drop(M.lock().unwrap());
388             drop(M.lock().unwrap());
389             M.destroy();
390         }
391     }
392
393     #[test]
394     fn lots_and_lots() {
395         static M: StaticMutex = MUTEX_INIT;
396         static mut CNT: u32 = 0;
397         const J: u32 = 1000;
398         const K: u32 = 3;
399
400         fn inc() {
401             for _ in 0..J {
402                 unsafe {
403                     let _g = M.lock().unwrap();
404                     CNT += 1;
405                 }
406             }
407         }
408
409         let (tx, rx) = channel();
410         for _ in 0..K {
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(); });
415         }
416
417         drop(tx);
418         for _ in 0..2 * K {
419             rx.recv().unwrap();
420         }
421         assert_eq!(unsafe {CNT}, J * K * 2);
422         unsafe {
423             M.destroy();
424         }
425     }
426
427     #[test]
428     fn try_lock() {
429         let m = Mutex::new(());
430         *m.try_lock().unwrap() = ();
431     }
432
433     #[test]
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
440             rx.recv().unwrap();
441             let &(ref lock, ref cvar) = &*packet2.0;
442             let mut lock = lock.lock().unwrap();
443             *lock = true;
444             cvar.notify_one();
445         });
446
447         let &(ref lock, ref cvar) = &*packet.0;
448         let mut lock = lock.lock().unwrap();
449         tx.send(()).unwrap();
450         assert!(!*lock);
451         while !*lock {
452             lock = cvar.wait(lock).unwrap();
453         }
454     }
455
456     #[test]
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();
461
462         let _t = thread::spawn(move || -> () {
463             rx.recv().unwrap();
464             let &(ref lock, ref cvar) = &*packet2.0;
465             let _g = lock.lock().unwrap();
466             cvar.notify_one();
467             // Parent should fail when it wakes up.
468             panic!();
469         });
470
471         let &(ref lock, ref cvar) = &*packet.0;
472         let mut lock = lock.lock().unwrap();
473         tx.send(()).unwrap();
474         while *lock == 1 {
475             match cvar.wait(lock) {
476                 Ok(l) => {
477                     lock = l;
478                     assert_eq!(*lock, 1);
479                 }
480                 Err(..) => break,
481             }
482         }
483     }
484
485     #[test]
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);
493         }).join();
494         assert!(arc.lock().is_err());
495         assert!(arc.is_poisoned());
496     }
497
498     #[test]
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();
510         });
511         rx.recv().unwrap();
512     }
513
514     #[test]
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|| -> () {
519             struct Unwinder {
520                 i: Arc<Mutex<i32>>,
521             }
522             impl Drop for Unwinder {
523                 fn drop(&mut self) {
524                     *self.i.lock().unwrap() += 1;
525                 }
526             }
527             let _u = Unwinder { i: arc2 };
528             panic!();
529         }).join();
530         let lock = arc.lock().unwrap();
531         assert_eq!(*lock, 2);
532     }
533 }