//! Timers (ADR 0004, Revision 5): one heap per scheduler thread, and a //! lock-free lower bound on the earliest deadline. //! //! - **Adding** a timer touches only the adding thread's heap, behind its //! own lock (another thread takes it only to fire timers), and lowers //! [`Timers::earliest`]. Actors waiting with timeouts on every thread no //! longer meet on one lock. //! - **Checking** whether a timer may be due, between slices, is one //! atomic load. //! - **Firing** takes timers out of every heap. One thread fires at a time //! (the [`Firing`] guard), and the due timers are woken in (deadline, //! pid) order, so the order is the single heap's: with one thread there //! is one heap, and `LOUISE_THREADS=1` still matches the interpreter. //! //! **The bound stays a lower bound** because it changes only under heap //! locks: an adder lowers it while holding its heap's lock, and the firing //! thread recomputes it while holding every heap's lock. So no timer is //! added between the firing thread's scan and its store. loom checks this //! (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt --release --lib timers`). use std::cmp::Reverse; use std::collections::BinaryHeap; #[cfg(loom)] use loom::sync::{ Mutex, MutexGuard, atomic::{AtomicU64, Ordering}, }; #[cfg(not(loom))] use std::sync::{ Mutex, MutexGuard, atomic::{AtomicU64, Ordering}, }; /// Wake actor `pid` at `deadline`, if it is still in wait number `wait` /// then (a timer whose wait has ended is dropped when it is met). #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub(crate) struct Timer { pub(crate) deadline: u64, pub(crate) pid: i64, pub(crate) wait: u64, } type Heap = BinaryHeap>; /// No deadline in any heap. const NONE: u64 = u64::MAX; pub(crate) struct Timers { /// One heap per scheduler thread, soonest first. heaps: Box<[Mutex]>, /// No deadline in a heap is earlier than this. It may be earlier than /// every deadline: timers whose wait ended are dropped lazily. earliest: AtomicU64, /// Held while timers are taken out of the heaps. firing: Mutex<()>, } impl Timers { pub(crate) fn new(threads: usize) -> Timers { Timers { heaps: (0..threads.max(1)) .map(|_| Mutex::new(BinaryHeap::new())) .collect(), earliest: AtomicU64::new(NONE), firing: Mutex::new(()), } } /// Add `timer` to heap `heap` (the calling scheduler thread's). pub(crate) fn add(&self, heap: usize, timer: Timer) { let mut heap = self.heaps[heap % self.heaps.len()] .lock() .expect("louise: timers poisoned"); heap.push(Reverse(timer)); // Under the heap's lock (see the module comment). The bound cannot // rise while we hold it, so it only needs writing when this // deadline is sooner: most timeouts are later than some other. if timer.deadline < self.earliest.load(Ordering::SeqCst) { self.earliest.fetch_min(timer.deadline, Ordering::SeqCst); } } /// Whether a timer may be due at `now` (a cheap check: the timers /// found due may all have ended their waits). pub(crate) fn maybe_due(&self, now: u64) -> bool { self.earliest.load(Ordering::SeqCst) <= now } /// Take the right to fire timers, waiting for it. pub(crate) fn firing(&self) -> Firing<'_> { Firing { timers: self, _guard: self.firing.lock().expect("louise: timers poisoned"), } } /// Take the right to fire timers, unless another thread has it. pub(crate) fn try_firing(&self) -> Option> { Some(Firing { timers: self, _guard: self.firing.try_lock().ok()?, }) } } /// The right to take timers out of the heaps (one thread at a time). pub(crate) struct Firing<'a> { timers: &'a Timers, _guard: MutexGuard<'a, ()>, } impl Firing<'_> { /// Visit every heap under every heap's lock (taken in order), then /// store the new bound: `visit` may pop timers. fn scan(&self, mut visit: impl FnMut(&mut Heap)) { let t = self.timers; let mut heaps: Vec> = t .heaps .iter() .map(|h| h.lock().expect("louise: timers poisoned")) .collect(); let mut earliest = NONE; for heap in &mut heaps { visit(heap); if let Some(Reverse(top)) = heap.peek() { earliest = earliest.min(top.deadline); } } t.earliest.store(earliest, Ordering::SeqCst); } /// The soonest deadline of a timer that `live` keeps. Timers it /// rejects are dropped on the way. pub(crate) fn next(&self, live: impl Fn(&Timer) -> bool) -> Option { let mut next = None::; self.scan(|heap| { while let Some(Reverse(top)) = heap.peek() { if live(top) { next = Some(next.map_or(top.deadline, |n| n.min(top.deadline))); break; } heap.pop(); } }); next } /// Take every timer due at `now`, in (deadline, pid) order. pub(crate) fn take_due(&self, now: u64) -> Vec { let mut due = Vec::new(); self.scan(|heap| { while heap.peek().is_some_and(|Reverse(top)| top.deadline <= now) { due.extend(heap.pop().map(|Reverse(t)| t)); } }); due.sort_unstable(); due } } #[cfg(all(test, loom))] mod loom_models { use super::*; use loom::sync::Arc; use loom::thread; fn timer(deadline: u64, pid: i64) -> Timer { Timer { deadline, pid, wait: 1, } } /// A thread adds a timer while another fires: either the firing thread /// took it, or the bound still shows it to the next check. #[test] fn add_while_firing() { loom::model(|| { let timers = Arc::new(Timers::new(2)); timers.add(0, timer(9, 0)); let adder = { let timers = timers.clone(); thread::spawn(move || timers.add(1, timer(5, 1))) }; let taken = timers.firing().take_due(5); adder.join().unwrap(); if !taken.iter().any(|t| t.pid == 1) { assert!(timers.maybe_due(5), "a due timer left unseen"); } assert!(!timers.maybe_due(4), "the bound goes no lower than a timer"); }); } /// Two threads add while a third looks for the next deadline: the bound /// ends at most at the soonest timer left. #[test] fn adds_while_scanning() { loom::model(|| { let timers = Arc::new(Timers::new(2)); let adders: Vec<_> = [(0, 7), (1, 3)] .into_iter() .map(|(heap, deadline)| { let timers = timers.clone(); thread::spawn(move || timers.add(heap, timer(deadline, heap as i64))) }) .collect(); let _ = timers.firing().next(|_| true); for adder in adders { adder.join().unwrap(); } assert!(timers.maybe_due(3), "a timer left unseen"); }); } } #[cfg(all(test, not(loom)))] mod tests { use super::*; fn timer(deadline: u64, pid: i64, wait: u64) -> Timer { Timer { deadline, pid, wait, } } #[test] fn due_timers_come_out_in_deadline_then_pid_order() { let timers = Timers::new(3); timers.add(2, timer(10, 4, 1)); timers.add(0, timer(10, 1, 1)); timers.add(1, timer(5, 9, 1)); timers.add(1, timer(10, 2, 1)); timers.add(0, timer(20, 3, 1)); assert!(timers.maybe_due(5) && !timers.maybe_due(4)); let due = timers.firing().take_due(10); let pids: Vec = due.iter().map(|t| t.pid).collect(); assert_eq!(pids, [9, 1, 2, 4]); assert!(!timers.maybe_due(19) && timers.maybe_due(20)); } #[test] fn next_skips_and_drops_ended_waits() { let timers = Timers::new(2); timers.add(0, timer(3, 1, 1)); timers.add(1, timer(4, 2, 1)); timers.add(1, timer(8, 3, 1)); let firing = timers.firing(); assert_eq!(firing.next(|t| t.pid == 3), Some(8)); // The ended ones are gone, and the bound follows. assert_eq!(firing.next(|_| true), Some(8)); drop(firing); assert!(!timers.maybe_due(7)); assert_eq!(timers.firing().take_due(100).len(), 1); assert_eq!(timers.firing().next(|_| true), None); assert!(!timers.maybe_due(u64::MAX - 1)); } #[test] fn one_thread_fires_at_a_time() { let timers = Timers::new(1); let firing = timers.firing(); assert!(timers.try_firing().is_none()); drop(firing); assert!(timers.try_firing().is_some()); } }