use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::cell::Cell;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicUsize, Ordering};
const SLOTS: usize = 128;
const RECOUNT: std::time::Duration = std::time::Duration::from_millis(2);
#[repr(align(128))]
struct Slot(RwLock<()>);
static GATE: [Slot; SLOTS] = [const { Slot(parking_lot::const_rwlock(())) }; SLOTS];
static IN_USE: AtomicUsize = AtomicUsize::new(0);
static TAKERS: AtomicUsize = AtomicUsize::new(0);
static LATE: Slot = Slot(parking_lot::const_rwlock(()));
static OVERFLOW: AtomicUsize = AtomicUsize::new(0);
const UNASSIGNED: usize = usize::MAX;
struct MySlot {
slot: Cell<usize>,
late: Cell<bool>,
}
#[cold]
fn assign() -> usize {
let next = IN_USE.fetch_add(1, Ordering::SeqCst);
let slot = if next < SLOTS {
next
} else {
IN_USE.store(SLOTS, Ordering::SeqCst);
OVERFLOW.fetch_add(1, Ordering::Relaxed) % SLOTS
};
MY_SLOT.with(|mine| {
mine.slot.set(slot);
mine.late.set(TAKERS.load(Ordering::SeqCst) > 0);
});
slot
}
#[inline]
fn my_slot() -> (usize, bool) {
let (slot, late) = MY_SLOT.with(|mine| (mine.slot.get(), mine.late.get()));
if slot == UNASSIGNED {
let slot = assign();
return (slot, MY_SLOT.with(|mine| mine.late.get()));
}
if late {
return (slot, still_late());
}
(slot, false)
}
#[cold]
fn still_late() -> bool {
if TAKERS.load(Ordering::SeqCst) == 0 {
MY_SLOT.with(|mine| mine.late.set(false));
false
} else {
true
}
}
struct Taking;
impl Taking {
fn begin() -> Taking {
TAKERS.fetch_add(1, Ordering::SeqCst);
Taking
}
}
impl Drop for Taking {
fn drop(&mut self) {
TAKERS.fetch_sub(1, Ordering::SeqCst);
}
}
thread_local! {
static MY_SLOT: MySlot = const {
MySlot {
slot: Cell::new(UNASSIGNED),
late: Cell::new(false),
}
};
static DEPTH: Cell<u32> = const { Cell::new(0) };
static ALONE: Cell<bool> = const { Cell::new(false) };
}
pub struct Guard {
_slot: Option<RwLockReadGuard<'static, ()>>,
_late: Option<RwLockReadGuard<'static, ()>>,
_not_send: PhantomData<*const ()>,
}
impl Drop for Guard {
fn drop(&mut self) {
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
#[inline]
pub fn enter() -> Guard {
let nested = DEPTH.with(|d| {
let depth = d.get();
d.set(depth + 1);
depth > 0
});
let (slot, late) = if nested {
(None, None)
} else {
let (slot, late) = my_slot();
let slot = GATE[slot].0.read();
(Some(slot), late.then(|| LATE.0.read_recursive()))
};
Guard {
_slot: slot,
_late: late,
_not_send: PhantomData,
}
}
#[inline]
pub fn enter_unless(
slice: std::time::Duration,
mut give_up: impl FnMut() -> bool,
) -> Option<Guard> {
let nested = DEPTH.with(|d| d.get() > 0);
let (slot, late) = if nested {
(None, None)
} else {
let (slot, late) = my_slot();
let mut wait_for = |gate: &'static RwLock<()>, late: bool| {
let at_once = if late {
gate.try_read_recursive()
} else {
gate.try_read()
};
if let Some(held) = at_once {
return Some(held);
}
loop {
let in_time = if late {
gate.try_read_recursive_for(slice)
} else {
gate.try_read_for(slice)
};
if let Some(held) = in_time {
return Some(held);
}
if give_up() {
return None;
}
}
};
let slot = wait_for(&GATE[slot].0, false)?;
let late = if late {
Some(wait_for(&LATE.0, true)?)
} else {
None
};
(Some(slot), late)
};
DEPTH.with(|d| d.set(d.get() + 1));
Some(Guard {
_slot: slot,
_late: late,
_not_send: PhantomData,
})
}
pub struct AloneGuard {
_slots: Vec<RwLockWriteGuard<'static, ()>>,
_taking: Option<Taking>,
outermost: bool,
_not_send: PhantomData<*const ()>,
}
impl Drop for AloneGuard {
fn drop(&mut self) {
if self.outermost {
ALONE.with(|a| a.set(false));
}
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
pub fn enter_alone() -> AloneGuard {
let nested = DEPTH.with(|d| {
let depth = d.get();
d.set(depth + 1);
depth > 0
});
if nested {
return AloneGuard {
_slots: Vec::new(),
_taking: None,
outermost: false,
_not_send: PhantomData,
};
}
let taking = Taking::begin();
let slots = close(None).expect("a taker without a way to give up gets the gate");
ALONE.with(|a| a.set(true));
AloneGuard {
_slots: slots,
_taking: Some(taking),
outermost: true,
_not_send: PhantomData,
}
}
pub fn enter_alone_unless(
slice: std::time::Duration,
mut give_up: impl FnMut() -> bool,
) -> Option<AloneGuard> {
if DEPTH.with(|d| d.get() > 0) {
return Some(enter_alone());
}
let taking = Taking::begin();
let slots = close(Some((slice, &mut give_up)))?;
DEPTH.with(|d| d.set(d.get() + 1));
ALONE.with(|a| a.set(true));
Some(AloneGuard {
_slots: slots,
_taking: Some(taking),
outermost: true,
_not_send: PhantomData,
})
}
fn close(
mut patience: Option<(std::time::Duration, &mut dyn FnMut() -> bool)>,
) -> Option<Vec<RwLockWriteGuard<'static, ()>>> {
let mut slots = Vec::with_capacity(IN_USE.load(Ordering::SeqCst).min(SLOTS) + 1);
loop {
let in_use = IN_USE.load(Ordering::SeqCst).min(SLOTS);
for slot in &GATE[slots.len()..in_use] {
let held = match &mut patience {
None => slot.0.write(),
Some((slice, give_up)) => match slot.0.try_write() {
Some(held) => held,
None => loop {
if let Some(held) = slot.0.try_write_for(*slice) {
break held;
}
if give_up() {
return None;
}
},
},
};
slots.push(held);
}
if let Some(late) = LATE.0.try_write_for(RECOUNT) {
slots.push(late);
return Some(slots);
}
if let Some((_, give_up)) = &mut patience
&& give_up()
{
return None;
}
}
}
#[inline]
pub fn taker_waiting() -> bool {
TAKERS.load(Ordering::Relaxed) > 0
}
#[inline]
pub fn alone_on_this_thread() -> bool {
ALONE.with(|a| a.get())
}
#[inline(always)]
pub fn skips(name: &str, cmd: &[&[u8]]) -> bool {
let sub = |word: &[u8]| cmd.get(1).is_some_and(|s| s.eq_ignore_ascii_case(word));
let arg = |at: usize, word: &[u8]| cmd.get(at).is_some_and(|s| s.eq_ignore_ascii_case(word));
match name {
"WAIT" | "WAITAOF" | "MIGRATE" | "SHUTDOWN" | "DEBUG" => true,
"CLUSTER" => {
sub(b"ADDSLOTS")
|| sub(b"ADDSLOTSRANGE")
|| (sub(b"SETSLOT") && (arg(3, b"IMPORTING") || arg(3, b"NODE")))
}
"SCRIPT" => sub(b"KILL"),
"FUNCTION" => sub(b"KILL") || sub(b"STATS"),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64};
use std::time::Duration;
#[test]
fn nothing_else_runs_while_the_gate_is_held_alone() {
let in_flight = Arc::new(AtomicU64::new(0));
let stop = Arc::new(AtomicBool::new(false));
let workers: Vec<_> = (0..6)
.map(|_| {
let in_flight = Arc::clone(&in_flight);
let stop = Arc::clone(&stop);
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let _guard = enter();
in_flight.fetch_add(1, Ordering::SeqCst);
std::thread::yield_now();
in_flight.fetch_sub(1, Ordering::SeqCst);
}
})
})
.collect();
for _ in 0..200 {
let _alone = enter_alone();
assert!(alone_on_this_thread());
for _ in 0..20 {
assert_eq!(in_flight.load(Ordering::SeqCst), 0);
}
}
assert!(!alone_on_this_thread());
stop.store(true, Ordering::Relaxed);
for w in workers {
w.join().unwrap();
}
}
#[test]
fn nesting_does_not_deadlock() {
let outer = enter_alone();
let inner = enter();
let script_in_transaction = enter_alone();
assert!(alone_on_this_thread());
drop(script_in_transaction);
assert!(alone_on_this_thread());
drop(inner);
drop(outer);
assert!(!alone_on_this_thread());
let command = enter();
let nested = enter_alone();
assert!(!alone_on_this_thread(), "it could not close the gate");
drop(nested);
drop(command);
let done = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&done);
let t = std::thread::spawn(move || {
let _alone = enter_alone();
flag.store(true, Ordering::SeqCst);
});
t.join().unwrap();
assert!(done.load(Ordering::SeqCst));
}
#[test]
fn commands_do_not_wait_for_each_other() {
for _ in 0..50 {
let mine = enter();
let entered = std::thread::spawn(|| {
let deadline = std::time::Instant::now() + Duration::from_millis(200);
enter_unless(Duration::from_millis(5), || {
std::time::Instant::now() > deadline
})
.is_some()
})
.join()
.unwrap();
drop(mine);
if entered {
return;
}
}
panic!("a command never got in beside another");
}
#[test]
fn the_commands_that_must_get_through() {
assert!(skips("SCRIPT", &[b"SCRIPT", b"kill"]));
assert!(!skips("SCRIPT", &[b"SCRIPT", b"LOAD", b"return 1"]));
assert!(skips("FUNCTION", &[b"FUNCTION", b"STATS"]));
assert!(skips("WAIT", &[b"WAIT", b"1", b"0"]));
assert!(skips("MIGRATE", &[b"MIGRATE"]));
assert!(!skips("GET", &[b"GET", b"k"]));
assert!(!skips("EXEC", &[b"EXEC"]));
}
#[test]
fn a_wait_for_the_gate_can_be_given_up() {
let (held_tx, held_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
let holder = std::thread::spawn(move || {
let _alone = enter_alone();
held_tx.send(()).unwrap();
release_rx.recv().unwrap();
});
held_rx.recv().unwrap();
let slice = Duration::from_millis(5);
let mut asked = 0;
assert!(
enter_unless(slice, || {
asked += 1;
asked == 3
})
.is_none()
);
assert_eq!(asked, 3);
assert!(enter_alone_unless(slice, || true).is_none());
assert!(!alone_on_this_thread());
release_tx.send(()).unwrap();
holder.join().unwrap();
assert!(enter_unless(slice, || false).is_some());
let alone = enter_alone_unless(slice, || false).expect("the gate is open");
assert!(alone_on_this_thread());
assert!(enter_unless(slice, || panic!("it does not wait")).is_some());
drop(alone);
assert!(!alone_on_this_thread());
}
}
#[cfg(test)]
mod late_threads {
use super::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64};
use std::time::Duration;
#[test]
fn late_threads_running_commands_back_to_back_do_not_starve_a_taker() {
let (held_tx, held_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
let holder = std::thread::spawn(move || {
let _command = enter();
held_tx.send(()).unwrap();
release_rx.recv().unwrap();
});
held_rx.recv().unwrap();
let (got_tx, got_rx) = std::sync::mpsc::channel();
let taker = std::thread::spawn(move || {
let _alone = enter_alone();
got_tx.send(()).unwrap();
});
std::thread::sleep(Duration::from_millis(50));
let stop = Arc::new(AtomicBool::new(false));
let crowd: Vec<_> = (0..6)
.map(|_| {
let stop = Arc::clone(&stop);
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let _command = enter();
std::thread::yield_now();
}
})
})
.collect();
std::thread::sleep(Duration::from_millis(50));
release_tx.send(()).unwrap();
holder.join().unwrap();
let got_in = got_rx.recv_timeout(Duration::from_secs(20)).is_ok();
stop.store(true, Ordering::Relaxed);
for thread in crowd {
thread.join().unwrap();
}
assert!(got_in, "the taker never got the gate");
taker.join().unwrap();
}
#[test]
fn a_thread_that_starts_while_the_gate_is_taken_is_kept_out() {
let in_flight = Arc::new(AtomicU64::new(0));
let stop = Arc::new(AtomicBool::new(false));
let spawners: Vec<_> = (0..4)
.map(|_| {
let in_flight = Arc::clone(&in_flight);
let stop = Arc::clone(&stop);
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let in_flight = Arc::clone(&in_flight);
std::thread::spawn(move || {
for _ in 0..3 {
let _command = enter();
in_flight.fetch_add(1, Ordering::SeqCst);
std::hint::spin_loop();
in_flight.fetch_sub(1, Ordering::SeqCst);
}
})
.join()
.unwrap();
}
})
})
.collect();
for _ in 0..2000 {
let _alone = enter_alone();
assert_eq!(
in_flight.load(Ordering::SeqCst),
0,
"a command ran beside it"
);
std::hint::spin_loop();
assert_eq!(
in_flight.load(Ordering::SeqCst),
0,
"a command started beside it"
);
}
stop.store(true, Ordering::Relaxed);
for spawner in spawners {
spawner.join().unwrap();
}
}
}