1pub mod deferred;
11
12use std::sync::{Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
13
14pub trait MutexRecover<T: ?Sized> {
16 fn lock_recover(&self) -> MutexGuard<'_, T>;
17}
18
19impl<T: ?Sized> MutexRecover<T> for Mutex<T> {
20 fn lock_recover(&self) -> MutexGuard<'_, T> {
21 self.lock().unwrap_or_else(PoisonError::into_inner)
22 }
23}
24
25pub trait RwLockRecover<T: ?Sized> {
28 fn read_recover(&self) -> RwLockReadGuard<'_, T>;
29 fn write_recover(&self) -> RwLockWriteGuard<'_, T>;
30}
31
32impl<T: ?Sized> RwLockRecover<T> for RwLock<T> {
33 fn read_recover(&self) -> RwLockReadGuard<'_, T> {
34 self.read().unwrap_or_else(PoisonError::into_inner)
35 }
36
37 fn write_recover(&self) -> RwLockWriteGuard<'_, T> {
38 self.write().unwrap_or_else(PoisonError::into_inner)
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45 use std::sync::Arc;
46
47 #[test]
48 fn a_poisoned_lock_still_hands_out_its_value() {
49 let mutex = Arc::new(Mutex::new(1));
50 let rwlock = Arc::new(RwLock::new(1));
51 let (m, r) = (Arc::clone(&mutex), Arc::clone(&rwlock));
52 let _ = std::thread::spawn(move || {
53 let _m = m.lock_recover();
54 let _r = r.write_recover();
55 panic!("poison both");
56 })
57 .join();
58 assert!(mutex.is_poisoned() && rwlock.is_poisoned());
59 *mutex.lock_recover() += 1;
60 *rwlock.write_recover() += 1;
61 assert_eq!((*mutex.lock_recover(), *rwlock.read_recover()), (2, 2));
62 }
63}