use core::cell::UnsafeCell;
use core::hint::spin_loop;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, Ordering};
pub struct SpinLock<T> {
locked: AtomicBool,
data: UnsafeCell<T>,
}
unsafe impl<T> Sync for SpinLock<T> {}
unsafe impl<T> Send for SpinLock<T> {}
impl<T> SpinLock<T> {
pub const fn new(value: T) -> Self {
SpinLock {
locked: AtomicBool::new(false),
data: UnsafeCell::new(value),
}
}
#[inline]
pub fn lock(&self) -> SpinGuard<'_, T> {
if self
.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
self.lock_contended();
}
SpinGuard { lock: self }
}
#[inline]
pub fn try_lock(&self) -> Option<SpinGuard<'_, T>> {
self.locked
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.ok()
.map(|_| SpinGuard { lock: self })
}
#[cfg(all(unix, not(miri)))]
pub fn acquire(&self) {
core::mem::forget(self.lock());
}
#[cfg(all(unix, not(miri)))]
pub unsafe fn release(&self) {
self.locked.store(false, Ordering::Release);
}
#[cold]
fn lock_contended(&self) {
let mut step = 0u32;
loop {
while self.locked.load(Ordering::Relaxed) {
if step < 7 {
for _ in 0..(1u32 << step) {
spin_loop();
}
step += 1;
} else {
std::thread::yield_now();
}
}
if self
.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
{
return;
}
}
}
}
pub struct SpinGuard<'a, T> {
lock: &'a SpinLock<T>,
}
impl<T> Deref for SpinGuard<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
impl<T> DerefMut for SpinGuard<'_, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
impl<T> Drop for SpinGuard<'_, T> {
#[inline]
fn drop(&mut self) {
self.lock.locked.store(false, Ordering::Release);
}
}