stdext/sync/
mutex.rs

1//! Extension traits for `std::sync::Mutex`.
2
3use std::sync::{Mutex, MutexGuard};
4
5/// Extension trait with useful methods for [`std::sync::Mutex`].
6///
7/// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
8pub trait MutexExt<T> {
9    /// Shorthand for `mutex.lock().unwrap()` with a better panic message.
10    ///
11    /// This method is intended to be used in situations where poisoned locks are
12    /// considered an exceptional situation and should always result in panic.
13    ///
14    /// # Examples
15    ///
16    /// ```
17    /// use std::sync::Mutex;
18    /// use stdext::prelude::*;
19    ///
20    /// let lock = Mutex::new(1);
21    ///
22    /// let n = lock.force_lock();
23    /// assert_eq!(*n, 1);
24    /// ```
25    fn force_lock(&self) -> MutexGuard<T>;
26}
27
28impl<T> MutexExt<T> for Mutex<T> {
29    fn force_lock(&self) -> MutexGuard<T> {
30        self.lock()
31            .expect("Unable to obtain lock: Mutex is poisoned")
32    }
33}