Skip to main content

panic_as_error/
locks.rs

1//! Taking a lock whose holder may have panicked.
2//!
3//! A panic in a thread that holds a `Mutex`, or holds an `RwLock` for
4//! writing, poisons the lock: std's way of saying the value may be
5//! half-changed. These helpers are for a lock whose every change is whole
6//! before anything in it can panic, so the caller uses the poisoned lock's
7//! value as it is. A
8//! lock whose change can leave half-made state needs a different answer, which
9//! its owner chooses.
10
11use std::sync::{Condvar, Mutex, MutexGuard, PoisonError, RwLock};
12use std::sync::{RwLockReadGuard, RwLockWriteGuard};
13
14/// Lock `mutex`, whose value no panic can leave half-changed.
15pub fn lock_unpoisoned<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
16    mutex.lock().unwrap_or_else(PoisonError::into_inner)
17}
18
19/// Read `lock`, whose value no panic can leave half-changed.
20pub fn read_unpoisoned<T: ?Sized>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
21    lock.read().unwrap_or_else(PoisonError::into_inner)
22}
23
24/// Write `lock`, whose value no panic can leave half-changed.
25pub fn write_unpoisoned<T: ?Sized>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
26    lock.write().unwrap_or_else(PoisonError::into_inner)
27}
28
29/// Return the value of `mutex`, which no panic can leave half-changed, and
30/// consume the mutex.
31pub fn into_unpoisoned<T>(mutex: Mutex<T>) -> T {
32    mutex.into_inner().unwrap_or_else(PoisonError::into_inner)
33}
34
35/// Wait on `condvar` with `guard`, the guard of a lock whose value no panic
36/// can leave half-changed.
37pub fn wait_unpoisoned<'a, T>(condvar: &Condvar, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
38    condvar.wait(guard).unwrap_or_else(PoisonError::into_inner)
39}
40
41#[cfg(test)]
42#[path = "locks_tests.rs"]
43mod tests;