use std::cell::UnsafeCell; use std::sync::atomic::{AtomicBool, Ordering}; pub struct SpinLock { locked: AtomicBool, value: UnsafeCell, } // The lock serializes access to the value between threads. unsafe impl Sync for SpinLock {} unsafe impl Send for SpinLock {} pub struct SpinLockGuard<'a, T> { lock: &'a SpinLock, } impl SpinLock { pub const fn new(value: T) -> Self { Self { locked: AtomicBool::new(false), value: UnsafeCell::new(value), } } pub fn lock(&self) -> SpinLockGuard<'_, T> { while self .locked .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) .is_err() { std::hint::spin_loop(); } SpinLockGuard { lock: self } } } impl std::ops::Deref for SpinLockGuard<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { unsafe { &*self.lock.value.get() } } } impl std::ops::DerefMut for SpinLockGuard<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { &mut *self.lock.value.get() } } } impl Drop for SpinLockGuard<'_, T> { fn drop(&mut self) { self.lock.locked.store(false, Ordering::Release); } }