use super::lock_trait::LockTrait;
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering;
pub struct SpinLock {
locked: AtomicBool,
}
pub struct SpinLockGuard<'a> {
lock: &'a SpinLock,
}
impl<'a> Drop for SpinLockGuard<'a> {
fn drop(&mut self) {
self.lock.locked.store(false, Ordering::Release);
}
}
impl LockTrait for SpinLock {
type Guard<'a>
= SpinLockGuard<'a>
where
Self: 'a;
fn lock(&self) -> Self::Guard<'_> {
while self
.locked
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_err()
{
core::hint::spin_loop();
}
SpinLockGuard { lock: self }
}
fn init() -> Self {
Self {
locked: AtomicBool::new(false),
}
}
}
unsafe impl Sync for SpinLock {}