]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mutex.rs
Auto merge of #27624 - apasel422:issue-27620, r=Gankro
[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 threads 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 threads, 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 ///         // threads 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 /// use std::sync::{Arc, Mutex};
89 /// use std::thread;
90 ///
91 /// let lock = Arc::new(Mutex::new(0_u32));
92 /// let lock2 = lock.clone();
93 ///
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 _lock = lock2.lock().unwrap();
98 ///
99 ///     // This panic while holding the lock (`_guard` is in scope) will poison
100 ///     // the mutex.
101 ///     panic!();
102 /// }).join();
103 ///
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(),
109 /// };
110 ///
111 /// *guard += 1;
112 /// ```
113 #[stable(feature = "rust1", since = "1.0.0")]
114 pub struct Mutex<T: ?Sized> {
115     // Note that this static mutex is in a *box*, not inlined into the struct
116     // itself. Once a native mutex has been used once, its address can never
117     // change (it can't be moved). This mutex type can be safely moved at any
118     // time, so to ensure that the native mutex is used correctly we box the
119     // inner lock to give it a constant address.
120     inner: Box<StaticMutex>,
121     data: UnsafeCell<T>,
122 }
123
124 // these are the only places where `T: Send` matters; all other
125 // functionality works fine on a single thread.
126 unsafe impl<T: ?Sized + Send> Send for Mutex<T> { }
127
128 unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { }
129
130 /// The static mutex type is provided to allow for static allocation of mutexes.
131 ///
132 /// Note that this is a separate type because using a Mutex correctly means that
133 /// it needs to have a destructor run. In Rust, statics are not allowed to have
134 /// destructors. As a result, a `StaticMutex` has one extra method when compared
135 /// to a `Mutex`, a `destroy` method. This method is unsafe to call, and
136 /// documentation can be found directly on the method.
137 ///
138 /// # Examples
139 ///
140 /// ```
141 /// #![feature(static_mutex)]
142 ///
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 = "static_mutex",
154            reason = "may be merged with Mutex in the future",
155            issue = "27717")]
156 pub struct StaticMutex {
157     lock: sys::Mutex,
158     poison: poison::Flag,
159 }
160
161 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
162 /// dropped (falls out of scope), the lock will be unlocked.
163 ///
164 /// The data protected by the mutex can be access through this guard via its
165 /// `Deref` and `DerefMut` implementations
166 #[must_use]
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct MutexGuard<'a, T: ?Sized + 'a> {
169     // funny underscores due to how Deref/DerefMut currently work (they
170     // disregard field privacy).
171     __lock: &'a StaticMutex,
172     __data: &'a UnsafeCell<T>,
173     __poison: poison::Guard,
174 }
175
176 impl<'a, T: ?Sized> !marker::Send for MutexGuard<'a, T> {}
177
178 /// Static initialization of a mutex. This constant can be used to initialize
179 /// other mutex constants.
180 #[unstable(feature = "static_mutex",
181            reason = "may be merged with Mutex in the future",
182            issue = "27717")]
183 pub const MUTEX_INIT: StaticMutex = StaticMutex::new();
184
185 impl<T> Mutex<T> {
186     /// Creates a new mutex in an unlocked state ready for use.
187     #[stable(feature = "rust1", since = "1.0.0")]
188     pub fn new(t: T) -> Mutex<T> {
189         Mutex {
190             inner: box StaticMutex::new(),
191             data: UnsafeCell::new(t),
192         }
193     }
194 }
195
196 impl<T: ?Sized> Mutex<T> {
197     /// Acquires a mutex, blocking the current thread until it is able to do so.
198     ///
199     /// This function will block the local thread until it is available to acquire
200     /// the mutex. Upon returning, the thread is the only thread with the mutex
201     /// held. An RAII guard is returned to allow scoped unlock of the lock. When
202     /// the guard goes out of scope, the mutex will be unlocked.
203     ///
204     /// # Failure
205     ///
206     /// If another user of this mutex panicked while holding the mutex, then
207     /// this call will return an error once the mutex is acquired.
208     #[stable(feature = "rust1", since = "1.0.0")]
209     pub fn lock(&self) -> LockResult<MutexGuard<T>> {
210         unsafe { self.inner.lock.lock() }
211         MutexGuard::new(&*self.inner, &self.data)
212     }
213
214     /// Attempts to acquire this lock.
215     ///
216     /// If the lock could not be acquired at this time, then `Err` is returned.
217     /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
218     /// guard is dropped.
219     ///
220     /// This function does not block.
221     ///
222     /// # Failure
223     ///
224     /// If another user of this mutex panicked while holding the mutex, then
225     /// this call will return failure if the mutex would otherwise be
226     /// acquired.
227     #[stable(feature = "rust1", since = "1.0.0")]
228     pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> {
229         if unsafe { self.inner.lock.try_lock() } {
230             Ok(try!(MutexGuard::new(&*self.inner, &self.data)))
231         } else {
232             Err(TryLockError::WouldBlock)
233         }
234     }
235
236     /// Determines whether the lock is poisoned.
237     ///
238     /// If another thread is active, the lock can still become poisoned at any
239     /// time.  You should not trust a `false` value for program correctness
240     /// without additional synchronization.
241     #[inline]
242     #[stable(feature = "sync_poison", since = "1.2.0")]
243     pub fn is_poisoned(&self) -> bool {
244         self.inner.poison.get()
245     }
246 }
247
248 #[stable(feature = "rust1", since = "1.0.0")]
249 impl<T: ?Sized> 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: ?Sized + 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::new(()));
274
275 #[unstable(feature = "static_mutex",
276            reason = "may be merged with Mutex in the future",
277            issue = "27717")]
278 impl StaticMutex {
279     /// Creates a new mutex in an unlocked state ready for use.
280     pub const fn new() -> StaticMutex {
281         StaticMutex {
282             lock: sys::Mutex::new(),
283             poison: poison::Flag::new(),
284         }
285     }
286
287     /// Acquires this lock, see `Mutex::lock`
288     #[inline]
289     pub fn lock(&'static self) -> LockResult<MutexGuard<()>> {
290         unsafe { self.lock.lock() }
291         MutexGuard::new(self, &DUMMY.0)
292     }
293
294     /// Attempts to grab this lock, see `Mutex::try_lock`
295     #[inline]
296     pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> {
297         if unsafe { self.lock.try_lock() } {
298             Ok(try!(MutexGuard::new(self, &DUMMY.0)))
299         } else {
300             Err(TryLockError::WouldBlock)
301         }
302     }
303
304     /// Deallocates resources associated with this static mutex.
305     ///
306     /// This method is unsafe because it provides no guarantees that there are
307     /// no active users of this mutex, and safety is not guaranteed if there are
308     /// active users of this mutex.
309     ///
310     /// This method is required to ensure that there are no memory leaks on
311     /// *all* platforms. It may be the case that some platforms do not leak
312     /// memory if this method is not called, but this is not guaranteed to be
313     /// true on all platforms.
314     pub unsafe fn destroy(&'static self) {
315         self.lock.destroy()
316     }
317 }
318
319 impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> {
320
321     fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>)
322            -> LockResult<MutexGuard<'mutex, T>> {
323         poison::map_result(lock.poison.borrow(), |guard| {
324             MutexGuard {
325                 __lock: lock,
326                 __data: data,
327                 __poison: guard,
328             }
329         })
330     }
331 }
332
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> {
335     type Target = T;
336
337     fn deref<'a>(&'a self) -> &'a T {
338         unsafe { &*self.__data.get() }
339     }
340 }
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> {
343     fn deref_mut<'a>(&'a mut self) -> &'a mut T {
344         unsafe { &mut *self.__data.get() }
345     }
346 }
347
348 #[stable(feature = "rust1", since = "1.0.0")]
349 impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> {
350     #[inline]
351     fn drop(&mut self) {
352         unsafe {
353             self.__lock.poison.done(&self.__poison);
354             self.__lock.lock.unlock();
355         }
356     }
357 }
358
359 pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex {
360     &guard.__lock.lock
361 }
362
363 pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
364     &guard.__lock.poison
365 }
366
367 #[cfg(test)]
368 mod tests {
369     use prelude::v1::*;
370
371     use sync::mpsc::channel;
372     use sync::{Arc, Mutex, StaticMutex, Condvar};
373     use thread;
374
375     struct Packet<T>(Arc<(Mutex<T>, Condvar)>);
376
377     unsafe impl<T: Send> Send for Packet<T> {}
378     unsafe impl<T> Sync for Packet<T> {}
379
380     #[test]
381     fn smoke() {
382         let m = Mutex::new(());
383         drop(m.lock().unwrap());
384         drop(m.lock().unwrap());
385     }
386
387     #[test]
388     fn smoke_static() {
389         static M: StaticMutex = StaticMutex::new();
390         unsafe {
391             drop(M.lock().unwrap());
392             drop(M.lock().unwrap());
393             M.destroy();
394         }
395     }
396
397     #[test]
398     fn lots_and_lots() {
399         static M: StaticMutex = StaticMutex::new();
400         static mut CNT: u32 = 0;
401         const J: u32 = 1000;
402         const K: u32 = 3;
403
404         fn inc() {
405             for _ in 0..J {
406                 unsafe {
407                     let _g = M.lock().unwrap();
408                     CNT += 1;
409                 }
410             }
411         }
412
413         let (tx, rx) = channel();
414         for _ in 0..K {
415             let tx2 = tx.clone();
416             thread::spawn(move|| { inc(); tx2.send(()).unwrap(); });
417             let tx2 = tx.clone();
418             thread::spawn(move|| { inc(); tx2.send(()).unwrap(); });
419         }
420
421         drop(tx);
422         for _ in 0..2 * K {
423             rx.recv().unwrap();
424         }
425         assert_eq!(unsafe {CNT}, J * K * 2);
426         unsafe {
427             M.destroy();
428         }
429     }
430
431     #[test]
432     fn try_lock() {
433         let m = Mutex::new(());
434         *m.try_lock().unwrap() = ();
435     }
436
437     #[test]
438     fn test_mutex_arc_condvar() {
439         let packet = Packet(Arc::new((Mutex::new(false), Condvar::new())));
440         let packet2 = Packet(packet.0.clone());
441         let (tx, rx) = channel();
442         let _t = thread::spawn(move|| {
443             // wait until parent gets in
444             rx.recv().unwrap();
445             let &(ref lock, ref cvar) = &*packet2.0;
446             let mut lock = lock.lock().unwrap();
447             *lock = true;
448             cvar.notify_one();
449         });
450
451         let &(ref lock, ref cvar) = &*packet.0;
452         let mut lock = lock.lock().unwrap();
453         tx.send(()).unwrap();
454         assert!(!*lock);
455         while !*lock {
456             lock = cvar.wait(lock).unwrap();
457         }
458     }
459
460     #[test]
461     fn test_arc_condvar_poison() {
462         let packet = Packet(Arc::new((Mutex::new(1), Condvar::new())));
463         let packet2 = Packet(packet.0.clone());
464         let (tx, rx) = channel();
465
466         let _t = thread::spawn(move || -> () {
467             rx.recv().unwrap();
468             let &(ref lock, ref cvar) = &*packet2.0;
469             let _g = lock.lock().unwrap();
470             cvar.notify_one();
471             // Parent should fail when it wakes up.
472             panic!();
473         });
474
475         let &(ref lock, ref cvar) = &*packet.0;
476         let mut lock = lock.lock().unwrap();
477         tx.send(()).unwrap();
478         while *lock == 1 {
479             match cvar.wait(lock) {
480                 Ok(l) => {
481                     lock = l;
482                     assert_eq!(*lock, 1);
483                 }
484                 Err(..) => break,
485             }
486         }
487     }
488
489     #[test]
490     fn test_mutex_arc_poison() {
491         let arc = Arc::new(Mutex::new(1));
492         assert!(!arc.is_poisoned());
493         let arc2 = arc.clone();
494         let _ = thread::spawn(move|| {
495             let lock = arc2.lock().unwrap();
496             assert_eq!(*lock, 2);
497         }).join();
498         assert!(arc.lock().is_err());
499         assert!(arc.is_poisoned());
500     }
501
502     #[test]
503     fn test_mutex_arc_nested() {
504         // Tests nested mutexes and access
505         // to underlying data.
506         let arc = Arc::new(Mutex::new(1));
507         let arc2 = Arc::new(Mutex::new(arc));
508         let (tx, rx) = channel();
509         let _t = thread::spawn(move|| {
510             let lock = arc2.lock().unwrap();
511             let lock2 = lock.lock().unwrap();
512             assert_eq!(*lock2, 1);
513             tx.send(()).unwrap();
514         });
515         rx.recv().unwrap();
516     }
517
518     #[test]
519     fn test_mutex_arc_access_in_unwind() {
520         let arc = Arc::new(Mutex::new(1));
521         let arc2 = arc.clone();
522         let _ = thread::spawn(move|| -> () {
523             struct Unwinder {
524                 i: Arc<Mutex<i32>>,
525             }
526             impl Drop for Unwinder {
527                 fn drop(&mut self) {
528                     *self.i.lock().unwrap() += 1;
529                 }
530             }
531             let _u = Unwinder { i: arc2 };
532             panic!();
533         }).join();
534         let lock = arc.lock().unwrap();
535         assert_eq!(*lock, 2);
536     }
537
538     // FIXME(#25351) needs deeply nested coercions of DST structs.
539     // #[test]
540     // fn test_mutex_unsized() {
541     //     let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]);
542     //     {
543     //         let b = &mut *mutex.lock().unwrap();
544     //         b[0] = 4;
545     //         b[2] = 5;
546     //     }
547     //     let comp: &[i32] = &[4, 2, 5];
548     //     assert_eq!(&*mutex.lock().unwrap(), comp);
549     // }
550 }