use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
pub struct Spinlock<T> {
data: UnsafeCell<T>,
flag: AtomicBool,
}
unsafe impl<T: Send> Send for Spinlock<T> {}
unsafe impl<T: Sync> Sync for Spinlock<T> {}
impl<T> Spinlock<T> {
pub fn new(data: T) -> Self {
Spinlock {
data: UnsafeCell::new(data),
flag: AtomicBool::new(false),
}
}
pub fn lock(&self) -> SpinlockGuard<'_, T> {
let mut spins = 0;
while self
.flag
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
if spins < 10 {
std::hint::spin_loop();
spins += 1;
} else {
thread::yield_now();
spins = 0; }
}
SpinlockGuard { lock: self }
}
fn unlock(&self) {
self.flag.store(false, Ordering::Release);
}
}
#[allow(clippy::needless_lifetimes)]
pub struct SpinlockGuard<'a, T> {
lock: &'a Spinlock<T>,
}
#[allow(clippy::needless_lifetimes)]
impl<'a, T> Drop for SpinlockGuard<'a, T> {
fn drop(&mut self) {
self.lock.unlock();
}
}
#[allow(clippy::needless_lifetimes)]
impl<'a, T> Deref for SpinlockGuard<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.lock.data.get() }
}
}
#[allow(clippy::needless_lifetimes)]
impl<'a, T> DerefMut for SpinlockGuard<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.lock.data.get() }
}
}