summaryrefslogtreecommitdiffstats
path: root/src/locks.rs
blob: ad66e6ff8ea05a028bdc7a74805b37a7901871f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//! Std locks without poisoning. A panic while one is held leaves its data as it was, and
//! every lock of this kind here guards counters, tables or caches that stay usable: so
//! the next user takes the data as it is instead of panicking too. (The tokio locks
//! around the document and the peers don't poison.)

use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};

pub(crate) trait MutexExt<T> {
    /// Locks, recovering from a poisoned mutex.
    fn lock_or_recover(&self) -> MutexGuard<'_, T>;
}

impl<T> MutexExt<T> for Mutex<T> {
    fn lock_or_recover(&self) -> MutexGuard<'_, T> {
        self.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
    }
}

pub(crate) trait RwLockExt<T> {
    /// Locks for reading, recovering from a poisoned lock.
    fn read_or_recover(&self) -> RwLockReadGuard<'_, T>;
    /// Locks for writing, recovering from a poisoned lock.
    fn write_or_recover(&self) -> RwLockWriteGuard<'_, T>;
}

impl<T> RwLockExt<T> for RwLock<T> {
    fn read_or_recover(&self) -> RwLockReadGuard<'_, T> {
        self.read().unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn write_or_recover(&self) -> RwLockWriteGuard<'_, T> {
        self.write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_panic_while_locked_doesnt_spread() {
        let mutex = std::sync::Arc::new(Mutex::new(1));
        let poisoner = std::sync::Arc::clone(&mutex);
        let _ = std::thread::spawn(move || {
            let _guard = poisoner.lock().unwrap();
            panic!("while holding the lock");
        })
        .join();
        assert!(mutex.is_poisoned());
        assert_eq!(*mutex.lock_or_recover(), 1);
    }
}