]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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 | ||
1a4d82fc | 11 | use cell::UnsafeCell; |
9346a6ac | 12 | use fmt; |
b039eaaf | 13 | use mem; |
1a4d82fc | 14 | use ops::{Deref, DerefMut}; |
b039eaaf | 15 | use ptr; |
1a4d82fc | 16 | use sys_common::mutex as sys; |
9346a6ac | 17 | use sys_common::poison::{self, TryLockError, TryLockResult, LockResult}; |
1a4d82fc JJ |
18 | |
19 | /// A mutual exclusion primitive useful for protecting shared data | |
20 | /// | |
21 | /// This mutex will block threads waiting for the lock to become available. The | |
22 | /// mutex can also be statically initialized or created via a `new` | |
23 | /// constructor. Each mutex has a type parameter which represents the data that | |
24 | /// it is protecting. The data can only be accessed through the RAII guards | |
25 | /// returned from `lock` and `try_lock`, which guarantees that the data is only | |
26 | /// ever accessed when the mutex is locked. | |
27 | /// | |
28 | /// # Poisoning | |
29 | /// | |
30 | /// The mutexes in this module implement a strategy called "poisoning" where a | |
31 | /// mutex is considered poisoned whenever a thread panics while holding the | |
cc61c64b | 32 | /// mutex. Once a mutex is poisoned, all other threads are unable to access the |
1a4d82fc JJ |
33 | /// data by default as it is likely tainted (some invariant is not being |
34 | /// upheld). | |
35 | /// | |
36 | /// For a mutex, this means that the `lock` and `try_lock` methods return a | |
37 | /// `Result` which indicates whether a mutex has been poisoned or not. Most | |
38 | /// usage of a mutex will simply `unwrap()` these results, propagating panics | |
39 | /// among threads to ensure that a possibly invalid invariant is not witnessed. | |
40 | /// | |
41 | /// A poisoned mutex, however, does not prevent all access to the underlying | |
c34b1796 | 42 | /// data. The `PoisonError` type has an `into_inner` method which will return |
1a4d82fc JJ |
43 | /// the guard that would have otherwise been returned on a successful lock. This |
44 | /// allows access to the data, despite the lock being poisoned. | |
45 | /// | |
46 | /// # Examples | |
47 | /// | |
c34b1796 | 48 | /// ``` |
1a4d82fc | 49 | /// use std::sync::{Arc, Mutex}; |
85aaf69f | 50 | /// use std::thread; |
1a4d82fc JJ |
51 | /// use std::sync::mpsc::channel; |
52 | /// | |
c34b1796 | 53 | /// const N: usize = 10; |
1a4d82fc JJ |
54 | /// |
55 | /// // Spawn a few threads to increment a shared variable (non-atomically), and | |
56 | /// // let the main thread know once all increments are done. | |
57 | /// // | |
bd371182 | 58 | /// // Here we're using an Arc to share memory among threads, and the data inside |
1a4d82fc JJ |
59 | /// // the Arc is protected with a mutex. |
60 | /// let data = Arc::new(Mutex::new(0)); | |
61 | /// | |
62 | /// let (tx, rx) = channel(); | |
cc61c64b | 63 | /// for _ in 0..N { |
1a4d82fc | 64 | /// let (data, tx) = (data.clone(), tx.clone()); |
85aaf69f | 65 | /// thread::spawn(move || { |
92a42be0 | 66 | /// // The shared state can only be accessed once the lock is held. |
1a4d82fc JJ |
67 | /// // Our non-atomic increment is safe because we're the only thread |
68 | /// // which can access the shared state when the lock is held. | |
69 | /// // | |
70 | /// // We unwrap() the return value to assert that we are not expecting | |
bd371182 | 71 | /// // threads to ever fail while holding the lock. |
1a4d82fc JJ |
72 | /// let mut data = data.lock().unwrap(); |
73 | /// *data += 1; | |
74 | /// if *data == N { | |
75 | /// tx.send(()).unwrap(); | |
76 | /// } | |
77 | /// // the lock is unlocked here when `data` goes out of scope. | |
78 | /// }); | |
79 | /// } | |
80 | /// | |
81 | /// rx.recv().unwrap(); | |
82 | /// ``` | |
83 | /// | |
84 | /// To recover from a poisoned mutex: | |
85 | /// | |
c34b1796 | 86 | /// ``` |
1a4d82fc | 87 | /// use std::sync::{Arc, Mutex}; |
85aaf69f | 88 | /// use std::thread; |
1a4d82fc | 89 | /// |
85aaf69f | 90 | /// let lock = Arc::new(Mutex::new(0_u32)); |
1a4d82fc JJ |
91 | /// let lock2 = lock.clone(); |
92 | /// | |
85aaf69f | 93 | /// let _ = thread::spawn(move || -> () { |
1a4d82fc JJ |
94 | /// // This thread will acquire the mutex first, unwrapping the result of |
95 | /// // `lock` because the lock has not been poisoned. | |
7453a54e | 96 | /// let _guard = lock2.lock().unwrap(); |
1a4d82fc JJ |
97 | /// |
98 | /// // This panic while holding the lock (`_guard` is in scope) will poison | |
99 | /// // the mutex. | |
100 | /// panic!(); | |
101 | /// }).join(); | |
102 | /// | |
103 | /// // The lock is poisoned by this point, but the returned result can be | |
104 | /// // pattern matched on to return the underlying guard on both branches. | |
105 | /// let mut guard = match lock.lock() { | |
106 | /// Ok(guard) => guard, | |
c34b1796 | 107 | /// Err(poisoned) => poisoned.into_inner(), |
1a4d82fc JJ |
108 | /// }; |
109 | /// | |
110 | /// *guard += 1; | |
111 | /// ``` | |
85aaf69f | 112 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 113 | pub struct Mutex<T: ?Sized> { |
5bcae85e SL |
114 | // Note that this mutex is in a *box*, not inlined into the struct itself. |
115 | // Once a native mutex has been used once, its address can never change (it | |
116 | // can't be moved). This mutex type can be safely moved at any time, so to | |
cc61c64b | 117 | // ensure that the native mutex is used correctly we box the inner mutex to |
5bcae85e SL |
118 | // give it a constant address. |
119 | inner: Box<sys::Mutex>, | |
120 | poison: poison::Flag, | |
1a4d82fc JJ |
121 | data: UnsafeCell<T>, |
122 | } | |
123 | ||
c34b1796 AL |
124 | // these are the only places where `T: Send` matters; all other |
125 | // functionality works fine on a single thread. | |
92a42be0 | 126 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 127 | unsafe impl<T: ?Sized + Send> Send for Mutex<T> { } |
92a42be0 | 128 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 129 | unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { } |
1a4d82fc | 130 | |
1a4d82fc JJ |
131 | /// An RAII implementation of a "scoped lock" of a mutex. When this structure is |
132 | /// dropped (falls out of scope), the lock will be unlocked. | |
133 | /// | |
cc61c64b | 134 | /// The data protected by the mutex can be accessed through this guard via its |
8bb4bdeb | 135 | /// [`Deref`] and [`DerefMut`] implementations. |
476ff2be | 136 | /// |
cc61c64b | 137 | /// This structure is created by the [`lock`] and [`try_lock`] methods on |
476ff2be SL |
138 | /// [`Mutex`]. |
139 | /// | |
8bb4bdeb XL |
140 | /// [`Deref`]: ../../std/ops/trait.Deref.html |
141 | /// [`DerefMut`]: ../../std/ops/trait.DerefMut.html | |
cc61c64b XL |
142 | /// [`lock`]: struct.Mutex.html#method.lock |
143 | /// [`try_lock`]: struct.Mutex.html#method.try_lock | |
476ff2be | 144 | /// [`Mutex`]: struct.Mutex.html |
1a4d82fc | 145 | #[must_use] |
85aaf69f | 146 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 147 | pub struct MutexGuard<'a, T: ?Sized + 'a> { |
1a4d82fc JJ |
148 | // funny underscores due to how Deref/DerefMut currently work (they |
149 | // disregard field privacy). | |
5bcae85e | 150 | __lock: &'a Mutex<T>, |
1a4d82fc | 151 | __poison: poison::Guard, |
1a4d82fc JJ |
152 | } |
153 | ||
92a42be0 | 154 | #[stable(feature = "rust1", since = "1.0.0")] |
7cac9316 XL |
155 | impl<'a, T: ?Sized> !Send for MutexGuard<'a, T> { } |
156 | #[stable(feature = "mutexguard", since = "1.19.0")] | |
157 | unsafe impl<'a, T: ?Sized + Sync> Sync for MutexGuard<'a, T> { } | |
85aaf69f | 158 | |
c34b1796 | 159 | impl<T> Mutex<T> { |
1a4d82fc | 160 | /// Creates a new mutex in an unlocked state ready for use. |
32a655c1 SL |
161 | /// |
162 | /// # Examples | |
163 | /// | |
164 | /// ``` | |
165 | /// use std::sync::Mutex; | |
166 | /// | |
167 | /// let mutex = Mutex::new(0); | |
168 | /// ``` | |
85aaf69f | 169 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 170 | pub fn new(t: T) -> Mutex<T> { |
3157f602 | 171 | let mut m = Mutex { |
5bcae85e SL |
172 | inner: box sys::Mutex::new(), |
173 | poison: poison::Flag::new(), | |
1a4d82fc | 174 | data: UnsafeCell::new(t), |
3157f602 XL |
175 | }; |
176 | unsafe { | |
5bcae85e | 177 | m.inner.init(); |
1a4d82fc | 178 | } |
3157f602 | 179 | m |
1a4d82fc | 180 | } |
d9579d0f | 181 | } |
1a4d82fc | 182 | |
d9579d0f | 183 | impl<T: ?Sized> Mutex<T> { |
bd371182 | 184 | /// Acquires a mutex, blocking the current thread until it is able to do so. |
1a4d82fc | 185 | /// |
bd371182 | 186 | /// This function will block the local thread until it is available to acquire |
cc61c64b | 187 | /// the mutex. Upon returning, the thread is the only thread with the lock |
1a4d82fc JJ |
188 | /// held. An RAII guard is returned to allow scoped unlock of the lock. When |
189 | /// the guard goes out of scope, the mutex will be unlocked. | |
190 | /// | |
a7813a04 XL |
191 | /// The exact behavior on locking a mutex in the thread which already holds |
192 | /// the lock is left unspecified. However, this function will not return on | |
193 | /// the second call (it might panic or deadlock, for example). | |
194 | /// | |
7453a54e | 195 | /// # Errors |
1a4d82fc JJ |
196 | /// |
197 | /// If another user of this mutex panicked while holding the mutex, then | |
198 | /// this call will return an error once the mutex is acquired. | |
a7813a04 XL |
199 | /// |
200 | /// # Panics | |
201 | /// | |
202 | /// This function might panic when called if the lock is already held by | |
203 | /// the current thread. | |
32a655c1 SL |
204 | /// |
205 | /// # Examples | |
206 | /// | |
207 | /// ``` | |
208 | /// use std::sync::{Arc, Mutex}; | |
209 | /// use std::thread; | |
210 | /// | |
211 | /// let mutex = Arc::new(Mutex::new(0)); | |
212 | /// let c_mutex = mutex.clone(); | |
213 | /// | |
214 | /// thread::spawn(move || { | |
215 | /// *c_mutex.lock().unwrap() = 10; | |
216 | /// }).join().expect("thread::spawn failed"); | |
217 | /// assert_eq!(*mutex.lock().unwrap(), 10); | |
218 | /// ``` | |
85aaf69f | 219 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 220 | pub fn lock(&self) -> LockResult<MutexGuard<T>> { |
7453a54e | 221 | unsafe { |
5bcae85e SL |
222 | self.inner.lock(); |
223 | MutexGuard::new(self) | |
7453a54e | 224 | } |
1a4d82fc JJ |
225 | } |
226 | ||
227 | /// Attempts to acquire this lock. | |
228 | /// | |
9346a6ac | 229 | /// If the lock could not be acquired at this time, then `Err` is returned. |
1a4d82fc JJ |
230 | /// Otherwise, an RAII guard is returned. The lock will be unlocked when the |
231 | /// guard is dropped. | |
232 | /// | |
233 | /// This function does not block. | |
234 | /// | |
7453a54e | 235 | /// # Errors |
1a4d82fc JJ |
236 | /// |
237 | /// If another user of this mutex panicked while holding the mutex, then | |
238 | /// this call will return failure if the mutex would otherwise be | |
239 | /// acquired. | |
32a655c1 SL |
240 | /// |
241 | /// # Examples | |
242 | /// | |
243 | /// ``` | |
244 | /// use std::sync::{Arc, Mutex}; | |
245 | /// use std::thread; | |
246 | /// | |
247 | /// let mutex = Arc::new(Mutex::new(0)); | |
248 | /// let c_mutex = mutex.clone(); | |
249 | /// | |
250 | /// thread::spawn(move || { | |
251 | /// let mut lock = c_mutex.try_lock(); | |
252 | /// if let Ok(ref mut mutex) = lock { | |
253 | /// **mutex = 10; | |
254 | /// } else { | |
255 | /// println!("try_lock failed"); | |
256 | /// } | |
257 | /// }).join().expect("thread::spawn failed"); | |
258 | /// assert_eq!(*mutex.lock().unwrap(), 10); | |
259 | /// ``` | |
85aaf69f | 260 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 261 | pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> { |
7453a54e | 262 | unsafe { |
5bcae85e SL |
263 | if self.inner.try_lock() { |
264 | Ok(MutexGuard::new(self)?) | |
7453a54e SL |
265 | } else { |
266 | Err(TryLockError::WouldBlock) | |
267 | } | |
1a4d82fc JJ |
268 | } |
269 | } | |
85aaf69f | 270 | |
cc61c64b | 271 | /// Determines whether the mutex is poisoned. |
85aaf69f | 272 | /// |
cc61c64b | 273 | /// If another thread is active, the mutex can still become poisoned at any |
32a655c1 | 274 | /// time. You should not trust a `false` value for program correctness |
85aaf69f | 275 | /// without additional synchronization. |
32a655c1 SL |
276 | /// |
277 | /// # Examples | |
278 | /// | |
279 | /// ``` | |
280 | /// use std::sync::{Arc, Mutex}; | |
281 | /// use std::thread; | |
282 | /// | |
283 | /// let mutex = Arc::new(Mutex::new(0)); | |
284 | /// let c_mutex = mutex.clone(); | |
285 | /// | |
286 | /// let _ = thread::spawn(move || { | |
287 | /// let _lock = c_mutex.lock().unwrap(); | |
288 | /// panic!(); // the mutex gets poisoned | |
289 | /// }).join(); | |
290 | /// assert_eq!(mutex.is_poisoned(), true); | |
291 | /// ``` | |
85aaf69f | 292 | #[inline] |
62682a34 | 293 | #[stable(feature = "sync_poison", since = "1.2.0")] |
85aaf69f | 294 | pub fn is_poisoned(&self) -> bool { |
5bcae85e | 295 | self.poison.get() |
85aaf69f | 296 | } |
b039eaaf SL |
297 | |
298 | /// Consumes this mutex, returning the underlying data. | |
299 | /// | |
7453a54e | 300 | /// # Errors |
b039eaaf SL |
301 | /// |
302 | /// If another user of this mutex panicked while holding the mutex, then | |
303 | /// this call will return an error instead. | |
32a655c1 SL |
304 | /// |
305 | /// # Examples | |
306 | /// | |
307 | /// ``` | |
308 | /// use std::sync::Mutex; | |
309 | /// | |
310 | /// let mutex = Mutex::new(0); | |
311 | /// assert_eq!(mutex.into_inner().unwrap(), 0); | |
312 | /// ``` | |
92a42be0 | 313 | #[stable(feature = "mutex_into_inner", since = "1.6.0")] |
b039eaaf SL |
314 | pub fn into_inner(self) -> LockResult<T> where T: Sized { |
315 | // We know statically that there are no outstanding references to | |
cc61c64b | 316 | // `self` so there's no need to lock the inner mutex. |
b039eaaf SL |
317 | // |
318 | // To get the inner value, we'd like to call `data.into_inner()`, | |
319 | // but because `Mutex` impl-s `Drop`, we can't move out of it, so | |
320 | // we'll have to destructure it manually instead. | |
321 | unsafe { | |
5bcae85e SL |
322 | // Like `let Mutex { inner, poison, data } = self`. |
323 | let (inner, poison, data) = { | |
324 | let Mutex { ref inner, ref poison, ref data } = self; | |
325 | (ptr::read(inner), ptr::read(poison), ptr::read(data)) | |
b039eaaf SL |
326 | }; |
327 | mem::forget(self); | |
5bcae85e SL |
328 | inner.destroy(); // Keep in sync with the `Drop` impl. |
329 | drop(inner); | |
b039eaaf | 330 | |
5bcae85e | 331 | poison::map_result(poison.borrow(), |_| data.into_inner()) |
b039eaaf SL |
332 | } |
333 | } | |
334 | ||
335 | /// Returns a mutable reference to the underlying data. | |
336 | /// | |
337 | /// Since this call borrows the `Mutex` mutably, no actual locking needs to | |
338 | /// take place---the mutable borrow statically guarantees no locks exist. | |
339 | /// | |
7453a54e | 340 | /// # Errors |
b039eaaf SL |
341 | /// |
342 | /// If another user of this mutex panicked while holding the mutex, then | |
343 | /// this call will return an error instead. | |
32a655c1 SL |
344 | /// |
345 | /// # Examples | |
346 | /// | |
347 | /// ``` | |
348 | /// use std::sync::Mutex; | |
349 | /// | |
350 | /// let mut mutex = Mutex::new(0); | |
351 | /// *mutex.get_mut().unwrap() = 10; | |
352 | /// assert_eq!(*mutex.lock().unwrap(), 10); | |
353 | /// ``` | |
92a42be0 | 354 | #[stable(feature = "mutex_get_mut", since = "1.6.0")] |
b039eaaf SL |
355 | pub fn get_mut(&mut self) -> LockResult<&mut T> { |
356 | // We know statically that there are no other references to `self`, so | |
cc61c64b | 357 | // there's no need to lock the inner mutex. |
b039eaaf | 358 | let data = unsafe { &mut *self.data.get() }; |
5bcae85e | 359 | poison::map_result(self.poison.borrow(), |_| data ) |
b039eaaf | 360 | } |
1a4d82fc JJ |
361 | } |
362 | ||
85aaf69f | 363 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 364 | unsafe impl<#[may_dangle] T: ?Sized> Drop for Mutex<T> { |
1a4d82fc JJ |
365 | fn drop(&mut self) { |
366 | // This is actually safe b/c we know that there is no further usage of | |
367 | // this mutex (it's up to the user to arrange for a mutex to get | |
368 | // dropped, that's not our job) | |
b039eaaf SL |
369 | // |
370 | // IMPORTANT: This code must be kept in sync with `Mutex::into_inner`. | |
5bcae85e | 371 | unsafe { self.inner.destroy() } |
1a4d82fc JJ |
372 | } |
373 | } | |
374 | ||
7cac9316 | 375 | #[stable(feature = "mutex_default", since = "1.10.0")] |
a7813a04 | 376 | impl<T: ?Sized + Default> Default for Mutex<T> { |
9e0c209e | 377 | /// Creates a `Mutex<T>`, with the `Default` value for T. |
a7813a04 XL |
378 | fn default() -> Mutex<T> { |
379 | Mutex::new(Default::default()) | |
380 | } | |
381 | } | |
382 | ||
c34b1796 | 383 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 384 | impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> { |
c34b1796 AL |
385 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
386 | match self.try_lock() { | |
d9579d0f | 387 | Ok(guard) => write!(f, "Mutex {{ data: {:?} }}", &*guard), |
c34b1796 | 388 | Err(TryLockError::Poisoned(err)) => { |
d9579d0f | 389 | write!(f, "Mutex {{ data: Poisoned({:?}) }}", &**err.get_ref()) |
c34b1796 AL |
390 | }, |
391 | Err(TryLockError::WouldBlock) => write!(f, "Mutex {{ <locked> }}") | |
392 | } | |
393 | } | |
394 | } | |
395 | ||
d9579d0f | 396 | impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> { |
5bcae85e | 397 | unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> { |
1a4d82fc JJ |
398 | poison::map_result(lock.poison.borrow(), |guard| { |
399 | MutexGuard { | |
400 | __lock: lock, | |
1a4d82fc | 401 | __poison: guard, |
1a4d82fc JJ |
402 | } |
403 | }) | |
404 | } | |
405 | } | |
406 | ||
85aaf69f | 407 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 408 | impl<'mutex, T: ?Sized> Deref for MutexGuard<'mutex, T> { |
1a4d82fc JJ |
409 | type Target = T; |
410 | ||
5bcae85e SL |
411 | fn deref(&self) -> &T { |
412 | unsafe { &*self.__lock.data.get() } | |
413 | } | |
1a4d82fc | 414 | } |
e9174d1e | 415 | |
85aaf69f | 416 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 417 | impl<'mutex, T: ?Sized> DerefMut for MutexGuard<'mutex, T> { |
5bcae85e SL |
418 | fn deref_mut(&mut self) -> &mut T { |
419 | unsafe { &mut *self.__lock.data.get() } | |
420 | } | |
1a4d82fc JJ |
421 | } |
422 | ||
85aaf69f | 423 | #[stable(feature = "rust1", since = "1.0.0")] |
d9579d0f | 424 | impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> { |
1a4d82fc JJ |
425 | #[inline] |
426 | fn drop(&mut self) { | |
427 | unsafe { | |
428 | self.__lock.poison.done(&self.__poison); | |
5bcae85e | 429 | self.__lock.inner.unlock(); |
1a4d82fc JJ |
430 | } |
431 | } | |
432 | } | |
433 | ||
8bb4bdeb | 434 | #[stable(feature = "std_debug", since = "1.16.0")] |
32a655c1 SL |
435 | impl<'a, T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'a, T> { |
436 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
437 | f.debug_struct("MutexGuard") | |
438 | .field("lock", &self.__lock) | |
439 | .finish() | |
440 | } | |
441 | } | |
442 | ||
041b39d2 XL |
443 | #[stable(feature = "std_guard_impls", since = "1.20.0")] |
444 | impl<'a, T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'a, T> { | |
445 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
446 | (**self).fmt(f) | |
447 | } | |
448 | } | |
449 | ||
d9579d0f | 450 | pub fn guard_lock<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex { |
5bcae85e | 451 | &guard.__lock.inner |
1a4d82fc JJ |
452 | } |
453 | ||
d9579d0f | 454 | pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag { |
1a4d82fc JJ |
455 | &guard.__lock.poison |
456 | } | |
457 | ||
c30ab7b3 | 458 | #[cfg(all(test, not(target_os = "emscripten")))] |
d9579d0f | 459 | mod tests { |
1a4d82fc | 460 | use sync::mpsc::channel; |
5bcae85e | 461 | use sync::{Arc, Mutex, Condvar}; |
b039eaaf | 462 | use sync::atomic::{AtomicUsize, Ordering}; |
85aaf69f | 463 | use thread; |
1a4d82fc | 464 | |
e9174d1e | 465 | struct Packet<T>(Arc<(Mutex<T>, Condvar)>); |
1a4d82fc | 466 | |
b039eaaf SL |
467 | #[derive(Eq, PartialEq, Debug)] |
468 | struct NonCopy(i32); | |
469 | ||
1a4d82fc JJ |
470 | #[test] |
471 | fn smoke() { | |
472 | let m = Mutex::new(()); | |
473 | drop(m.lock().unwrap()); | |
474 | drop(m.lock().unwrap()); | |
475 | } | |
476 | ||
1a4d82fc JJ |
477 | #[test] |
478 | fn lots_and_lots() { | |
c34b1796 AL |
479 | const J: u32 = 1000; |
480 | const K: u32 = 3; | |
1a4d82fc | 481 | |
5bcae85e SL |
482 | let m = Arc::new(Mutex::new(0)); |
483 | ||
484 | fn inc(m: &Mutex<u32>) { | |
85aaf69f | 485 | for _ in 0..J { |
5bcae85e | 486 | *m.lock().unwrap() += 1; |
1a4d82fc JJ |
487 | } |
488 | } | |
489 | ||
490 | let (tx, rx) = channel(); | |
85aaf69f | 491 | for _ in 0..K { |
1a4d82fc | 492 | let tx2 = tx.clone(); |
5bcae85e SL |
493 | let m2 = m.clone(); |
494 | thread::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); }); | |
1a4d82fc | 495 | let tx2 = tx.clone(); |
5bcae85e SL |
496 | let m2 = m.clone(); |
497 | thread::spawn(move|| { inc(&m2); tx2.send(()).unwrap(); }); | |
1a4d82fc JJ |
498 | } |
499 | ||
500 | drop(tx); | |
85aaf69f | 501 | for _ in 0..2 * K { |
1a4d82fc JJ |
502 | rx.recv().unwrap(); |
503 | } | |
5bcae85e | 504 | assert_eq!(*m.lock().unwrap(), J * K * 2); |
1a4d82fc JJ |
505 | } |
506 | ||
507 | #[test] | |
508 | fn try_lock() { | |
509 | let m = Mutex::new(()); | |
510 | *m.try_lock().unwrap() = (); | |
511 | } | |
512 | ||
b039eaaf SL |
513 | #[test] |
514 | fn test_into_inner() { | |
515 | let m = Mutex::new(NonCopy(10)); | |
516 | assert_eq!(m.into_inner().unwrap(), NonCopy(10)); | |
517 | } | |
518 | ||
519 | #[test] | |
520 | fn test_into_inner_drop() { | |
521 | struct Foo(Arc<AtomicUsize>); | |
522 | impl Drop for Foo { | |
523 | fn drop(&mut self) { | |
524 | self.0.fetch_add(1, Ordering::SeqCst); | |
525 | } | |
526 | } | |
527 | let num_drops = Arc::new(AtomicUsize::new(0)); | |
528 | let m = Mutex::new(Foo(num_drops.clone())); | |
529 | assert_eq!(num_drops.load(Ordering::SeqCst), 0); | |
530 | { | |
531 | let _inner = m.into_inner().unwrap(); | |
532 | assert_eq!(num_drops.load(Ordering::SeqCst), 0); | |
533 | } | |
534 | assert_eq!(num_drops.load(Ordering::SeqCst), 1); | |
535 | } | |
536 | ||
537 | #[test] | |
538 | fn test_into_inner_poison() { | |
539 | let m = Arc::new(Mutex::new(NonCopy(10))); | |
540 | let m2 = m.clone(); | |
541 | let _ = thread::spawn(move || { | |
542 | let _lock = m2.lock().unwrap(); | |
543 | panic!("test panic in inner thread to poison mutex"); | |
544 | }).join(); | |
545 | ||
546 | assert!(m.is_poisoned()); | |
547 | match Arc::try_unwrap(m).unwrap().into_inner() { | |
548 | Err(e) => assert_eq!(e.into_inner(), NonCopy(10)), | |
549 | Ok(x) => panic!("into_inner of poisoned Mutex is Ok: {:?}", x), | |
550 | } | |
551 | } | |
552 | ||
553 | #[test] | |
554 | fn test_get_mut() { | |
555 | let mut m = Mutex::new(NonCopy(10)); | |
556 | *m.get_mut().unwrap() = NonCopy(20); | |
557 | assert_eq!(m.into_inner().unwrap(), NonCopy(20)); | |
558 | } | |
559 | ||
560 | #[test] | |
561 | fn test_get_mut_poison() { | |
562 | let m = Arc::new(Mutex::new(NonCopy(10))); | |
563 | let m2 = m.clone(); | |
564 | let _ = thread::spawn(move || { | |
565 | let _lock = m2.lock().unwrap(); | |
566 | panic!("test panic in inner thread to poison mutex"); | |
567 | }).join(); | |
568 | ||
569 | assert!(m.is_poisoned()); | |
570 | match Arc::try_unwrap(m).unwrap().get_mut() { | |
571 | Err(e) => assert_eq!(*e.into_inner(), NonCopy(10)), | |
572 | Ok(x) => panic!("get_mut of poisoned Mutex is Ok: {:?}", x), | |
573 | } | |
574 | } | |
575 | ||
1a4d82fc JJ |
576 | #[test] |
577 | fn test_mutex_arc_condvar() { | |
578 | let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); | |
579 | let packet2 = Packet(packet.0.clone()); | |
580 | let (tx, rx) = channel(); | |
85aaf69f | 581 | let _t = thread::spawn(move|| { |
1a4d82fc JJ |
582 | // wait until parent gets in |
583 | rx.recv().unwrap(); | |
584 | let &(ref lock, ref cvar) = &*packet2.0; | |
585 | let mut lock = lock.lock().unwrap(); | |
586 | *lock = true; | |
587 | cvar.notify_one(); | |
588 | }); | |
589 | ||
590 | let &(ref lock, ref cvar) = &*packet.0; | |
591 | let mut lock = lock.lock().unwrap(); | |
592 | tx.send(()).unwrap(); | |
593 | assert!(!*lock); | |
594 | while !*lock { | |
595 | lock = cvar.wait(lock).unwrap(); | |
596 | } | |
597 | } | |
598 | ||
599 | #[test] | |
600 | fn test_arc_condvar_poison() { | |
85aaf69f | 601 | let packet = Packet(Arc::new((Mutex::new(1), Condvar::new()))); |
1a4d82fc JJ |
602 | let packet2 = Packet(packet.0.clone()); |
603 | let (tx, rx) = channel(); | |
604 | ||
85aaf69f | 605 | let _t = thread::spawn(move || -> () { |
1a4d82fc JJ |
606 | rx.recv().unwrap(); |
607 | let &(ref lock, ref cvar) = &*packet2.0; | |
608 | let _g = lock.lock().unwrap(); | |
609 | cvar.notify_one(); | |
610 | // Parent should fail when it wakes up. | |
611 | panic!(); | |
612 | }); | |
613 | ||
614 | let &(ref lock, ref cvar) = &*packet.0; | |
615 | let mut lock = lock.lock().unwrap(); | |
616 | tx.send(()).unwrap(); | |
617 | while *lock == 1 { | |
618 | match cvar.wait(lock) { | |
619 | Ok(l) => { | |
620 | lock = l; | |
621 | assert_eq!(*lock, 1); | |
622 | } | |
623 | Err(..) => break, | |
624 | } | |
625 | } | |
626 | } | |
627 | ||
628 | #[test] | |
629 | fn test_mutex_arc_poison() { | |
85aaf69f SL |
630 | let arc = Arc::new(Mutex::new(1)); |
631 | assert!(!arc.is_poisoned()); | |
1a4d82fc | 632 | let arc2 = arc.clone(); |
85aaf69f | 633 | let _ = thread::spawn(move|| { |
1a4d82fc JJ |
634 | let lock = arc2.lock().unwrap(); |
635 | assert_eq!(*lock, 2); | |
636 | }).join(); | |
637 | assert!(arc.lock().is_err()); | |
85aaf69f | 638 | assert!(arc.is_poisoned()); |
1a4d82fc JJ |
639 | } |
640 | ||
641 | #[test] | |
642 | fn test_mutex_arc_nested() { | |
643 | // Tests nested mutexes and access | |
644 | // to underlying data. | |
85aaf69f | 645 | let arc = Arc::new(Mutex::new(1)); |
1a4d82fc JJ |
646 | let arc2 = Arc::new(Mutex::new(arc)); |
647 | let (tx, rx) = channel(); | |
85aaf69f | 648 | let _t = thread::spawn(move|| { |
1a4d82fc JJ |
649 | let lock = arc2.lock().unwrap(); |
650 | let lock2 = lock.lock().unwrap(); | |
651 | assert_eq!(*lock2, 1); | |
652 | tx.send(()).unwrap(); | |
653 | }); | |
654 | rx.recv().unwrap(); | |
655 | } | |
656 | ||
657 | #[test] | |
658 | fn test_mutex_arc_access_in_unwind() { | |
85aaf69f | 659 | let arc = Arc::new(Mutex::new(1)); |
1a4d82fc | 660 | let arc2 = arc.clone(); |
85aaf69f | 661 | let _ = thread::spawn(move|| -> () { |
1a4d82fc | 662 | struct Unwinder { |
c34b1796 | 663 | i: Arc<Mutex<i32>>, |
1a4d82fc JJ |
664 | } |
665 | impl Drop for Unwinder { | |
666 | fn drop(&mut self) { | |
667 | *self.i.lock().unwrap() += 1; | |
668 | } | |
669 | } | |
670 | let _u = Unwinder { i: arc2 }; | |
671 | panic!(); | |
672 | }).join(); | |
673 | let lock = arc.lock().unwrap(); | |
674 | assert_eq!(*lock, 2); | |
675 | } | |
d9579d0f | 676 | |
b039eaaf SL |
677 | #[test] |
678 | fn test_mutex_unsized() { | |
679 | let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); | |
680 | { | |
681 | let b = &mut *mutex.lock().unwrap(); | |
682 | b[0] = 4; | |
683 | b[2] = 5; | |
684 | } | |
685 | let comp: &[i32] = &[4, 2, 5]; | |
686 | assert_eq!(&*mutex.lock().unwrap(), comp); | |
687 | } | |
1a4d82fc | 688 | } |