From dcd92954f448c0ece06bc35a2d69500273b141c8 Mon Sep 17 00:00:00 2001 From: krishvishal Date: Thu, 27 Mar 2025 18:45:05 +0530 Subject: [PATCH] Remove unlock method and move it to guard's drop. This makes the interface safe and prevents unlocking while still holding the guard --- core/fast_lock.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/core/fast_lock.rs b/core/fast_lock.rs index f7f955bfa..33933e772 100644 --- a/core/fast_lock.rs +++ b/core/fast_lock.rs @@ -6,7 +6,7 @@ use std::{ #[derive(Debug)] pub struct SpinLock { - lock: AtomicBool, + locked: AtomicBool, value: UnsafeCell, } @@ -16,7 +16,7 @@ pub struct SpinLockGuard<'a, T> { impl<'a, T> Drop for SpinLockGuard<'a, T> { fn drop(&mut self) { - self.lock.unlock(); + self.lock.locked.store(false, Ordering::Release); } } @@ -40,21 +40,17 @@ unsafe impl Sync for SpinLock {} impl SpinLock { pub fn new(value: T) -> Self { Self { - lock: AtomicBool::new(false), + locked: AtomicBool::new(false), value: UnsafeCell::new(value), } } pub fn lock(&self) -> SpinLockGuard { - while self.lock.swap(true, Ordering::Acquire) { + while self.locked.swap(true, Ordering::Acquire) { std::hint::spin_loop(); } SpinLockGuard { lock: self } } - - pub fn unlock(&self) { - self.lock.store(false, Ordering::Release); - } } #[cfg(test)]