use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::cell::Cell;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicUsize, Ordering};
const SLOTS: usize = 128;
#[repr(align(128))]
struct Slot(RwLock<()>);
static GATE: [Slot; SLOTS] = [const { Slot(parking_lot::const_rwlock(())) }; SLOTS];
static NEXT_SLOT: AtomicUsize = AtomicUsize::new(0);
thread_local! {
static MY_SLOT: usize = NEXT_SLOT.fetch_add(1, Ordering::Relaxed) % SLOTS;
static DEPTH: Cell<u32> = const { Cell::new(0) };
}
pub struct WriteGuard {
_slot: Option<RwLockReadGuard<'static, ()>>,
_not_send: PhantomData<*const ()>,
}
impl Drop for WriteGuard {
fn drop(&mut self) {
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
#[inline]
pub fn enter() -> WriteGuard {
let nested = DEPTH.with(|d| {
let depth = d.get();
d.set(depth + 1);
depth > 0
});
let slot = if nested {
None
} else {
Some(GATE[MY_SLOT.with(|s| *s)].0.read())
};
WriteGuard {
_slot: slot,
_not_send: PhantomData,
}
}
pub fn held_by_this_thread() -> bool {
DEPTH.with(|d| d.get() > 0)
}
pub struct CutGuard(#[allow(dead_code)] Vec<RwLockWriteGuard<'static, ()>>);
pub fn cut() -> Option<CutGuard> {
if held_by_this_thread() {
return None;
}
Some(CutGuard(GATE.iter().map(|slot| slot.0.write()).collect()))
}
pub fn wait_out_writes(deadline: std::time::Instant, go_on: impl Fn() -> bool) -> bool {
const STEP: std::time::Duration = std::time::Duration::from_millis(1);
let mine = held_by_this_thread().then(|| MY_SLOT.with(|s| *s));
for (at, slot) in GATE.iter().enumerate() {
if mine == Some(at) {
continue;
}
while slot.0.try_write_for(STEP).is_none() {
if std::time::Instant::now() >= deadline || !go_on() {
return false;
}
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64};
use std::time::Duration;
#[test]
fn a_cut_never_observes_a_half_finished_write() {
let applied = Arc::new(AtomicU64::new(0));
let propagated = Arc::new(AtomicU64::new(0));
let stop = Arc::new(AtomicBool::new(false));
let writers: Vec<_> = (0..4)
.map(|_| {
let applied = Arc::clone(&applied);
let propagated = Arc::clone(&propagated);
let stop = Arc::clone(&stop);
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let _gate = enter();
applied.fetch_add(1, Ordering::SeqCst);
std::thread::yield_now();
propagated.fetch_add(1, Ordering::SeqCst);
}
})
})
.collect();
for _ in 0..200 {
let _cut = cut();
let a = applied.load(Ordering::SeqCst);
let p = propagated.load(Ordering::SeqCst);
assert_eq!(
a, p,
"a write was applied but not yet propagated at the cut"
);
}
stop.store(true, Ordering::Relaxed);
for w in writers {
w.join().unwrap();
}
}
#[test]
fn nesting_on_one_thread_cannot_self_deadlock() {
let outer = enter();
assert!(held_by_this_thread());
{
let _inner = enter();
assert!(held_by_this_thread());
}
assert!(held_by_this_thread(), "the outer guard is still held");
assert!(
cut().is_none(),
"a cut from inside a write must be declined"
);
drop(outer);
assert!(!held_by_this_thread());
assert!(cut().is_some());
}
#[test]
fn the_writes_in_the_gate_are_waited_out_without_closing_it() {
let entered = Arc::new(AtomicBool::new(false));
let release = Arc::new(AtomicBool::new(false));
let writer = {
let (entered, release) = (Arc::clone(&entered), Arc::clone(&release));
std::thread::spawn(move || {
let _gate = enter();
entered.store(true, Ordering::SeqCst);
while !release.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(1));
}
})
};
while !entered.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(1));
}
let far = || std::time::Instant::now() + Duration::from_secs(30);
assert!(!wait_out_writes(far(), || false), "it did not give up");
let soon = std::time::Instant::now() + Duration::from_millis(20);
assert!(
!wait_out_writes(soon, || true),
"it waited past its deadline"
);
let started = std::time::Instant::now();
let releaser = {
let release = Arc::clone(&release);
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
release.store(true, Ordering::SeqCst);
})
};
assert!(wait_out_writes(far(), || true));
assert!(
started.elapsed() >= Duration::from_millis(40),
"the write in the gate was not waited for"
);
writer.join().unwrap();
releaser.join().unwrap();
}
#[test]
fn writers_do_not_exclude_one_another() {
let _a = enter();
let done = Arc::new(AtomicBool::new(false));
let done2 = Arc::clone(&done);
let t = std::thread::spawn(move || {
let _b = enter();
done2.store(true, Ordering::SeqCst);
});
for _ in 0..200 {
if done.load(Ordering::SeqCst) {
break;
}
std::thread::sleep(Duration::from_millis(5));
}
assert!(done.load(Ordering::SeqCst), "a second writer was blocked");
t.join().unwrap();
}
}