From 8be852662a432d96553fcf7a9fc57c4f3c92baae Mon Sep 17 00:00:00 2001 From: Mica White Date: Mon, 8 Dec 2025 20:03:40 -0500 Subject: Stuff --- src/mutex/mutex.rs | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) mode change 100644 => 100755 src/mutex/mutex.rs (limited to 'src/mutex/mutex.rs') diff --git a/src/mutex/mutex.rs b/src/mutex/mutex.rs old mode 100644 new mode 100755 index 05b10db..475c3ae --- a/src/mutex/mutex.rs +++ b/src/mutex/mutex.rs @@ -229,6 +229,33 @@ impl Mutex { } impl Mutex { + /// 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 Mutex { } } + /// 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, -- cgit v1.2.3