use core::cell::UnsafeCell;
use core::hint::spin_loop;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicBool, Ordering};
use crate::context::internal::SelfContainedContext;
const MAX_SPINLOCK_ATTEMPTS: usize = 128;
pub struct SpinLock<T> {
flag: AtomicBool,
data: UnsafeCell<T>,
}
unsafe impl<T: Send> Sync for SpinLock<T> {}
impl SpinLock<SelfContainedContext> {
pub const fn new() -> Self {
Self {
flag: AtomicBool::new(false),
data: UnsafeCell::new(SelfContainedContext::new_uninitialized()),
}
}
}
impl Default for SpinLock<SelfContainedContext> {
fn default() -> Self { Self::new() }
}
#[cfg(test)]
impl SpinLock<u64> {
pub const fn new(v: u64) -> Self {
Self { flag: AtomicBool::new(false), data: UnsafeCell::new(v) }
}
}
impl<T> SpinLock<T> {
pub fn try_lock(&self) -> Option<SpinLockGuard<'_, T>> {
for _ in 0..MAX_SPINLOCK_ATTEMPTS {
if self.flag.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_ok()
{
return Some(SpinLockGuard { lock: self });
}
spin_loop();
}
None
}
#[inline(always)]
unsafe fn unlock(&self) { self.flag.store(false, Ordering::Release); }
}
pub struct SpinLockGuard<'a, T> {
lock: &'a SpinLock<T>,
}
impl<T> Deref for SpinLockGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.lock.data.get() }
}
}
impl<T> DerefMut for SpinLockGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.lock.data.get() }
}
}
impl<T> Drop for SpinLockGuard<'_, T> {
fn drop(&mut self) {
unsafe {
self.lock.unlock();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const SPINLOCK_TEST_VAL: u64 = 100;
#[test]
fn basic_lock_unlock() {
let spinlock = SpinLock::<u64>::new(SPINLOCK_TEST_VAL);
let guard = spinlock.try_lock().expect("Should be able to acquire lock");
assert_eq!(*guard, SPINLOCK_TEST_VAL);
drop(guard);
let guard2 = spinlock.try_lock().expect("Should be able to reacquire lock");
assert_eq!(*guard2, SPINLOCK_TEST_VAL);
}
#[test]
fn modify_data() {
let spinlock = SpinLock::<u64>::new(SPINLOCK_TEST_VAL);
{
let mut guard = spinlock.try_lock().expect("Should be able to acquire lock");
*guard = 42;
}
let guard = spinlock.try_lock().expect("Should be able to reacquire lock");
assert_eq!(*guard, 42);
}
#[test]
fn contention_single_thread() {
let spinlock = SpinLock::<u64>::new(SPINLOCK_TEST_VAL);
let _guard1 = spinlock.try_lock().expect("Should be able to acquire lock");
let result = spinlock.try_lock();
assert!(result.is_none(), "Should not be able to acquire lock twice");
}
#[test]
fn guard_deref() {
let spinlock = SpinLock::<u64>::new(SPINLOCK_TEST_VAL);
let guard = spinlock.try_lock().expect("Should be able to acquire lock");
assert_eq!(*guard, SPINLOCK_TEST_VAL);
let value: u64 = *guard;
assert_eq!(value, SPINLOCK_TEST_VAL);
}
#[test]
fn guard_deref_mut() {
let spinlock = SpinLock::<u64>::new(SPINLOCK_TEST_VAL);
let mut guard = spinlock.try_lock().expect("Should be able to acquire lock");
*guard += 50;
assert_eq!(*guard, 150);
*guard = guard.wrapping_add(10);
assert_eq!(*guard, 160);
}
}
#[cfg(all(test, feature = "std"))]
mod std_tests {
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use super::*;
const SPINLOCK_TEST_VAL: u64 = 100;
#[test]
fn multiple_threads_no_contention() {
let spinlock = Arc::new(SpinLock::<u64>::new(SPINLOCK_TEST_VAL));
let mut handles = vec![];
for i in 1..=3 {
let spinlock_clone = Arc::clone(&spinlock);
let handle = thread::spawn(move || {
let mut guard = spinlock_clone.try_lock().expect("Should acquire lock");
let old_value = *guard;
*guard = old_value + i;
});
handles.push(handle);
thread::sleep(Duration::from_millis(10));
}
for handle in handles {
handle.join().expect("Thread should complete successfully");
}
let guard = spinlock.try_lock().expect("Should be able to acquire lock");
assert_eq!(*guard, 106);
}
#[test]
fn multiple_threads_contention() {
let spinlock = Arc::new(SpinLock::<u64>::new(SPINLOCK_TEST_VAL));
let mut handles = vec![];
for i in 1..=3 {
let spinlock_clone = Arc::clone(&spinlock);
let handle = thread::spawn(move || {
loop {
if let Some(mut guard) = spinlock_clone.try_lock() {
let old_value = *guard;
*guard = old_value + i;
thread::sleep(Duration::from_millis(10));
break;
}
}
});
handles.push(handle);
}
for handle in handles {
handle.join().expect("Thread should complete successfully");
}
let guard = spinlock.try_lock().expect("Should be able to acquire lock");
assert_eq!(*guard, 106);
}
}