use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, Ordering};
pub struct SpinLock<T> {
locked: AtomicBool,
value: UnsafeCell<T>,
}
unsafe impl<T: Send> Sync for SpinLock<T> {}
unsafe impl<T: Send> Send for SpinLock<T> {}
impl<T> SpinLock<T> {
pub const fn new(value: T) -> Self {
SpinLock {
locked: AtomicBool::new(false),
value: UnsafeCell::new(value),
}
}
pub fn lock(&self) -> SpinGuard<'_, T> {
while self
.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
while self.locked.load(Ordering::Relaxed) {
core::hint::spin_loop();
}
}
SpinGuard { lock: self }
}
}
pub struct SpinGuard<'a, T> {
lock: &'a SpinLock<T>,
}
impl<T> Deref for SpinGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.value.get() }
}
}
impl<T> DerefMut for SpinGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.value.get() }
}
}
impl<T> Drop for SpinGuard<'_, T> {
fn drop(&mut self) {
self.lock.locked.store(false, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lock_gives_mutable_access() {
let lock = SpinLock::new(0u32);
{
let mut g = lock.lock();
*g += 41;
*g += 1;
}
assert_eq!(*lock.lock(), 42);
}
#[test]
fn usable_as_static() {
static COUNTER: SpinLock<u32> = SpinLock::new(0);
*COUNTER.lock() += 1;
assert_eq!(*COUNTER.lock(), 1);
}
}