use core::sync::atomic::{self, AtomicUsize, Ordering};
use Backoff;
pub struct SeqLock {
state: AtomicUsize,
}
impl SeqLock {
pub const INIT: Self = Self {
state: AtomicUsize::new(0),
};
#[inline]
pub fn optimistic_read(&self) -> Option<usize> {
let state = self.state.load(Ordering::Acquire);
if state == 1 {
None
} else {
Some(state)
}
}
#[inline]
pub fn validate_read(&self, stamp: usize) -> bool {
atomic::fence(Ordering::Acquire);
self.state.load(Ordering::Relaxed) == stamp
}
#[inline]
pub fn write(&'static self) -> SeqLockWriteGuard {
let backoff = Backoff::new();
loop {
let previous = self.state.swap(1, Ordering::Acquire);
if previous != 1 {
atomic::fence(Ordering::Release);
return SeqLockWriteGuard {
lock: self,
state: previous,
};
}
backoff.snooze();
}
}
}
pub struct SeqLockWriteGuard {
lock: &'static SeqLock,
state: usize,
}
impl SeqLockWriteGuard {
#[inline]
pub fn abort(self) {
self.lock.state.store(self.state, Ordering::Release);
}
}
impl Drop for SeqLockWriteGuard {
#[inline]
fn drop(&mut self) {
self.lock
.state
.store(self.state.wrapping_add(2), Ordering::Release);
}
}