pub trait MutexExtensions<T: Send> {
// Required methods
fn lock_safe(&self, context: &str) -> DMSCLockResult<MutexGuard<'_, T>>;
fn try_lock_safe(
&self,
context: &str,
) -> DMSCLockResult<Option<MutexGuard<'_, T>>>;
}Expand description
Extension trait providing safe lock acquisition for Mutex.
This trait adds a lock_safe method to Mutex that returns a Result
instead of panicking when the lock is poisoned.
Required Methods§
Sourcefn lock_safe(&self, context: &str) -> DMSCLockResult<MutexGuard<'_, T>>
fn lock_safe(&self, context: &str) -> DMSCLockResult<MutexGuard<'_, T>>
Acquires a lock safely, returning a Result instead of panicking.
This method attempts to acquire the mutex lock. If a previous holder panicked while holding the lock (poisoned), this method returns an error instead of panicking.
§Arguments
context: A description of what is being locked for error messages
§Returns
Ok(MutexGuard<T>)if the lock was acquired successfullyErr(DMSCLockError)if the lock could not be acquired
§Examples
ⓘ
use std::sync::Mutex;
use dmsc::core::lock::MutexExtensions;
let mutex = Mutex::new(42);
match mutex.lock_safe("important_data") {
Ok(guard) => println!("Value: {}", *guard),
Err(e) => println!("Failed to acquire lock: {}", e),
}Sourcefn try_lock_safe(
&self,
context: &str,
) -> DMSCLockResult<Option<MutexGuard<'_, T>>>
fn try_lock_safe( &self, context: &str, ) -> DMSCLockResult<Option<MutexGuard<'_, T>>>
Attempts to acquire the lock, returning immediately if unavailable.
This method tries to acquire the mutex lock without blocking. If the lock is held by another thread, it returns an error immediately.
§Arguments
context: A description of what is being locked for error messages
§Returns
Ok(Some(MutexGuard<T>))if the lock was acquiredOk(None)if the lock is held by another threadErr(DMSCLockError)if the lock is poisoned