// src/mutex/spin.rs
/// Try to lock this [`SpinMutex`], returning a lock guard if successful.
///
/// # Example
///
/// ```
/// let lock = spin::mutex::SpinMutex::<_>::new(42);
///
/// let maybe_guard = lock.try_lock();
/// assert!(maybe_guard.is_some());
///
/// // `maybe_guard` is still held, so the second call fails
/// let maybe_guard2 = lock.try_lock();
/// assert!(maybe_guard2.is_none());
/// ```
#[inline(always)]
pub fn try_lock(&self) -> Option<SpinMutexGuard<T>> {
// The reason for using a strong compare_exchange is explained here:
// https://github.com/Amanieu/parking_lot/pull/207#issuecomment-575869107
if self
.lock
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
{
Some(SpinMutexGuard {
lock: &self.lock,
data: unsafe { &mut *self.data.get() },
})
} else {
None
}
}
/// Try to lock this [`SpinMutex`], returning a lock guard if succesful.
///
/// Unlike [`SpinMutex::try_lock`], this function is allowed to spuriously fail even when the mutex is unlocked,
/// which can result in more efficient code on some platforms.
#[inline(always)]
pub fn try_lock_weak(&self) -> Option<SpinMutexGuard<T>> {
if self
.lock
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
{
Some(SpinMutexGuard {
lock: &self.lock,
data: unsafe { &mut *self.data.get() },
})
} else {
None
}
}
Just as the title explained.
However, I was wondering why try_lock_weak exists. Is it kept for future implementation?
Just as the title explained. However, I was wondering why
try_lock_weak
exists. Is it kept for future implementation?