mvdnes / spin-rs

Spin-based synchronization primitives
MIT License
485 stars 92 forks source link

`try_lock` and `try_lock_weak` share exactly the same implementation in spin.rs #161

Closed ChenRuiwei closed 9 months ago

ChenRuiwei commented 9 months ago
// 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?

taiki-e commented 9 months ago

exactly the same implementation

No, try_lock uses compare_exchange (strong) and try_lock_weak uses compareexchangeweak. The latter can spuriously fail.

ChenRuiwei commented 9 months ago

Sorry, my bad. I better go to see an eye docter.