sync: Add is_poisoned to Mutex and RwLock

This commit is contained in:
Keegan McAllister 2015-01-23 11:47:04 -08:00
parent 7ebf9bc5c2
commit 96c3a13680
2 changed files with 26 additions and 0 deletions

View File

@ -228,6 +228,17 @@ impl<T: Send> Mutex<T> {
Err(TryLockError::WouldBlock) Err(TryLockError::WouldBlock)
} }
} }
/// Determine whether the lock is poisoned.
///
/// If another thread is active, the lock can still become poisoned at any
/// time. You should not trust a `false` value for program correctness
/// without additional synchronization.
#[inline]
#[unstable(feature = "std_misc")]
pub fn is_poisoned(&self) -> bool {
self.inner.poison.get()
}
} }
#[unsafe_destructor] #[unsafe_destructor]
@ -458,12 +469,14 @@ mod test {
#[test] #[test]
fn test_mutex_arc_poison() { fn test_mutex_arc_poison() {
let arc = Arc::new(Mutex::new(1)); let arc = Arc::new(Mutex::new(1));
assert!(!arc.is_poisoned());
let arc2 = arc.clone(); let arc2 = arc.clone();
let _ = Thread::scoped(move|| { let _ = Thread::scoped(move|| {
let lock = arc2.lock().unwrap(); let lock = arc2.lock().unwrap();
assert_eq!(*lock, 2); assert_eq!(*lock, 2);
}).join(); }).join();
assert!(arc.lock().is_err()); assert!(arc.lock().is_err());
assert!(arc.is_poisoned());
} }
#[test] #[test]

View File

@ -237,6 +237,17 @@ impl<T: Send + Sync> RwLock<T> {
Err(TryLockError::WouldBlock) Err(TryLockError::WouldBlock)
} }
} }
/// Determine whether the lock is poisoned.
///
/// If another thread is active, the lock can still become poisoned at any
/// time. You should not trust a `false` value for program correctness
/// without additional synchronization.
#[inline]
#[unstable(feature = "std_misc")]
pub fn is_poisoned(&self) -> bool {
self.inner.poison.get()
}
} }
#[unsafe_destructor] #[unsafe_destructor]
@ -451,12 +462,14 @@ mod tests {
#[test] #[test]
fn test_rw_arc_poison_ww() { fn test_rw_arc_poison_ww() {
let arc = Arc::new(RwLock::new(1)); let arc = Arc::new(RwLock::new(1));
assert!(!arc.is_poisoned());
let arc2 = arc.clone(); let arc2 = arc.clone();
let _: Result<uint, _> = Thread::scoped(move|| { let _: Result<uint, _> = Thread::scoped(move|| {
let _lock = arc2.write().unwrap(); let _lock = arc2.write().unwrap();
panic!(); panic!();
}).join(); }).join();
assert!(arc.write().is_err()); assert!(arc.write().is_err());
assert!(arc.is_poisoned());
} }
#[test] #[test]