Skip to main content

conmonrs/
mutex.rs

1//! Lock helpers.
2
3use std::sync::{Mutex, MutexGuard, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
4
5/// Lock a mutex, also if a panic poisoned it. A panic aborts release builds,
6/// so this only matters for tests and debug builds. Treating a poisoned lock
7/// like an empty one there would hide the state behind it, like the children
8/// which are waited for.
9pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
10    mutex.lock().unwrap_or_else(PoisonError::into_inner)
11}
12
13/// Lock a read write lock for reading, also if a panic poisoned it, see
14/// [`lock`].
15pub(crate) fn read<T>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
16    lock.read().unwrap_or_else(PoisonError::into_inner)
17}
18
19/// Lock a read write lock for writing, also if a panic poisoned it, see
20/// [`lock`].
21pub(crate) fn write<T>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
22    lock.write().unwrap_or_else(PoisonError::into_inner)
23}