use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use crate::backoff::Backoff;
pub(crate) struct Spinlock<T> {
flag: AtomicBool,
value: UnsafeCell<T>,
}
unsafe impl<T: Send> Send for Spinlock<T> {}
unsafe impl<T: Send> Sync for Spinlock<T> {}
impl<T> Spinlock<T> {
#[inline(always)]
pub fn new(value: T) -> Self {
Self {
flag: AtomicBool::new(false),
value: UnsafeCell::new(value),
}
}
#[inline]
pub(crate) fn lock(&self) -> SpinlockGuard<T> {
let backoff = Backoff::default();
while self.flag.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
while self.flag.load(Ordering::Relaxed) {
backoff.snooze();
}
}
SpinlockGuard { parent: self }
}
}
pub struct SpinlockGuard<'a, T> {
parent: &'a Spinlock<T>,
}
impl<T> Drop for SpinlockGuard<'_, T> {
#[inline(always)]
fn drop(&mut self) {
self.parent.flag.store(false, Ordering::Release);
}
}
impl<T> Deref for SpinlockGuard<'_, T> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
unsafe { &*self.parent.value.get() }
}
}
impl<T> DerefMut for SpinlockGuard<'_, T> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.parent.value.get() }
}
}