use std::sync::{
Mutex,
MutexGuard,
};
pub trait MutexExt<T> {
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| {
tracing::error!(
"recovering from a poisoned mutex - a prior panic may have left shared state \
inconsistent, this is always a bug"
);
poisoned.into_inner()
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lock_or_recover_survives_a_prior_panic_instead_of_panicking_forever() {
let mutex = Mutex::new(0);
let panicked = std::panic::catch_unwind(|| {
let mut guard = mutex.lock().unwrap();
*guard = 1;
panic!("simulated bug while holding the lock");
});
assert!(panicked.is_err());
assert!(
mutex.is_poisoned(),
"the mutex must actually be poisoned by now"
);
let guard = mutex.lock_or_recover();
assert_eq!(
*guard, 1,
"the write made before the panic must still be visible"
);
}
}