summaryrefslogtreecommitdiff
path: root/src/mutex
diff options
context:
space:
mode:
Diffstat (limited to 'src/mutex')
-rwxr-xr-x[-rw-r--r--]src/mutex/guard.rs0
-rwxr-xr-x[-rw-r--r--]src/mutex/mutex.rs62
2 files changed, 62 insertions, 0 deletions
diff --git a/src/mutex/guard.rs b/src/mutex/guard.rs
index d88fded..d88fded 100644..100755
--- a/src/mutex/guard.rs
+++ b/src/mutex/guard.rs
diff --git a/src/mutex/mutex.rs b/src/mutex/mutex.rs
index 05b10db..475c3ae 100644..100755
--- a/src/mutex/mutex.rs
+++ b/src/mutex/mutex.rs
@@ -229,6 +229,33 @@ impl<T: ?Sized, R> Mutex<T, R> {
}
impl<T: ?Sized, R: RawMutex> Mutex<T, R> {
+ /// Acquires a lock on the mutex, blocking until it is safe to do so, and then
+ /// unlocks the mutex after the provided function returns.
+ ///
+ /// This function is useful to ensure that a Mutex is never accidentally
+ /// locked forever by leaking the `MutexGuard`. Even if the function panics,
+ /// this function will gracefully notice the panic, and unlock the mutex.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if the provided function also panics. However,
+ /// mutex will be safely unlocked in this case, allowing the mutex to be
+ /// locked again later.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// use happylock::{ThreadKey, Mutex};
+ ///
+ /// let mut key = ThreadKey::get().unwrap();
+ /// let mutex = Mutex::new(42);
+ ///
+ /// let x = mutex.scoped_lock(&mut key, |number| {
+ /// *number += 5;
+ /// *number
+ /// });
+ /// assert_eq!(x, 47);
+ /// ```
pub fn scoped_lock<'a, Ret>(
&'a self,
key: impl Keyable,
@@ -254,6 +281,41 @@ impl<T: ?Sized, R: RawMutex> Mutex<T, R> {
}
}
+ /// Attempts to acquire the `Mutex` without blocking, and then unlocks it once
+ /// the provided function returns.
+ ///
+ /// This function implements a non-blocking variant of [`scoped_lock`]. Unlike
+ /// `scoped_lock`, if the mutex is not already unlocked, then the provided
+ /// function will not run, and the given [`Keyable`] is returned.
+ ///
+ /// # Errors
+ ///
+ /// If the mutex is already locked, then the provided function will not run.
+ /// `Err` is returned with the given key.
+ ///
+ /// # Panics
+ ///
+ /// If the provided function panics, then the panic will be bubbled up and
+ /// rethrown. The mutex will also be gracefully unlocked, allowing the mutex
+ /// to be locked again.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use happylock::{Mutex, ThreadKey};
+ ///
+ /// let mut key = ThreadKey::get().unwrap();
+ /// let mutex = Mutex::new(42);
+ ///
+ /// let result = mutex.scoped_try_lock(&mut key, |num| {
+ /// *num
+ /// });
+ ///
+ /// match result {
+ /// Ok(val) => println!("The number is {val}"),
+ /// Err(_) => unreachable!(),
+ /// }
+ /// ```
pub fn scoped_try_lock<'a, Key: Keyable, Ret>(
&'a self,
key: Key,