Skip to main content

tilo_lock/
lib.rs

1//! Locking that outlives a panicking holder: a poisoned lock hands back its guard
2//! instead of an error.
3//!
4//! A release build aborts on a panic outside `tilo_rt::panic_boundary::isolate`, so
5//! no thread meets a lock another poisoned, and state shared across such a boundary
6//! must treat a poisoned lock as unavailable. Debug and test builds unwind
7//! everywhere, where recovering keeps one failed test from cascading into every
8//! later lock of the same state.
9
10pub mod deferred;
11
12use std::sync::{Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
13
14/// [`Mutex::lock`], recovering the guard of a poisoned mutex.
15pub 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
25/// [`RwLock::read`] and [`RwLock::write`], recovering the guard of a poisoned
26/// lock.
27pub 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}