tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

270 lignes · 9156 octetsBrut · Historique
1//! Timers (ADR 0004, Revision 5): one heap per scheduler thread, and a
2//! lock-free lower bound on the earliest deadline.
3//!
4//! - **Adding** a timer touches only the adding thread's heap, behind its
5//! own lock (another thread takes it only to fire timers), and lowers
6//! [`Timers::earliest`]. Actors waiting with timeouts on every thread no
7//! longer meet on one lock.
8//! - **Checking** whether a timer may be due, between slices, is one
9//! atomic load.
10//! - **Firing** takes timers out of every heap. One thread fires at a time
11//! (the [`Firing`] guard), and the due timers are woken in (deadline,
12//! pid) order, so the order is the single heap's: with one thread there
13//! is one heap, and `LOUISE_THREADS=1` still matches the interpreter.
14//!
15//! **The bound stays a lower bound** because it changes only under heap
16//! locks: an adder lowers it while holding its heap's lock, and the firing
17//! thread recomputes it while holding every heap's lock. So no timer is
18//! added between the firing thread's scan and its store. loom checks this
19//! (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt --release --lib timers`).
20
21use std::cmp::Reverse;
22use std::collections::BinaryHeap;
23
24#[cfg(loom)]
25use loom::sync::{
26 Mutex, MutexGuard,
27 atomic::{AtomicU64, Ordering},
28};
29#[cfg(not(loom))]
30use std::sync::{
31 Mutex, MutexGuard,
32 atomic::{AtomicU64, Ordering},
33};
34
35/// Wake actor `pid` at `deadline`, if it is still in wait number `wait`
36/// then (a timer whose wait has ended is dropped when it is met).
37#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
38pub(crate) struct Timer {
39 pub(crate) deadline: u64,
40 pub(crate) pid: i64,
41 pub(crate) wait: u64,
42}
43
44type Heap = BinaryHeap<Reverse<Timer>>;
45
46/// No deadline in any heap.
47const NONE: u64 = u64::MAX;
48
49pub(crate) struct Timers {
50 /// One heap per scheduler thread, soonest first.
51 heaps: Box<[Mutex<Heap>]>,
52 /// No deadline in a heap is earlier than this. It may be earlier than
53 /// every deadline: timers whose wait ended are dropped lazily.
54 earliest: AtomicU64,
55 /// Held while timers are taken out of the heaps.
56 firing: Mutex<()>,
57}
58
59impl Timers {
60 pub(crate) fn new(threads: usize) -> Timers {
61 Timers {
62 heaps: (0..threads.max(1))
63 .map(|_| Mutex::new(BinaryHeap::new()))
64 .collect(),
65 earliest: AtomicU64::new(NONE),
66 firing: Mutex::new(()),
67 }
68 }
69
70 /// Add `timer` to heap `heap` (the calling scheduler thread's).
71 pub(crate) fn add(&self, heap: usize, timer: Timer) {
72 let mut heap = self.heaps[heap % self.heaps.len()]
73 .lock()
74 .expect("louise: timers poisoned");
75 heap.push(Reverse(timer));
76 // Under the heap's lock (see the module comment). The bound cannot
77 // rise while we hold it, so it only needs writing when this
78 // deadline is sooner: most timeouts are later than some other.
79 if timer.deadline < self.earliest.load(Ordering::SeqCst) {
80 self.earliest.fetch_min(timer.deadline, Ordering::SeqCst);
81 }
82 }
83
84 /// Whether a timer may be due at `now` (a cheap check: the timers
85 /// found due may all have ended their waits).
86 pub(crate) fn maybe_due(&self, now: u64) -> bool {
87 self.earliest.load(Ordering::SeqCst) <= now
88 }
89
90 /// Take the right to fire timers, waiting for it.
91 pub(crate) fn firing(&self) -> Firing<'_> {
92 Firing {
93 timers: self,
94 _guard: self.firing.lock().expect("louise: timers poisoned"),
95 }
96 }
97
98 /// Take the right to fire timers, unless another thread has it.
99 pub(crate) fn try_firing(&self) -> Option<Firing<'_>> {
100 Some(Firing {
101 timers: self,
102 _guard: self.firing.try_lock().ok()?,
103 })
104 }
105}
106
107/// The right to take timers out of the heaps (one thread at a time).
108pub(crate) struct Firing<'a> {
109 timers: &'a Timers,
110 _guard: MutexGuard<'a, ()>,
111}
112
113impl Firing<'_> {
114 /// Visit every heap under every heap's lock (taken in order), then
115 /// store the new bound: `visit` may pop timers.
116 fn scan(&self, mut visit: impl FnMut(&mut Heap)) {
117 let t = self.timers;
118 let mut heaps: Vec<MutexGuard<'_, Heap>> = t
119 .heaps
120 .iter()
121 .map(|h| h.lock().expect("louise: timers poisoned"))
122 .collect();
123 let mut earliest = NONE;
124 for heap in &mut heaps {
125 visit(heap);
126 if let Some(Reverse(top)) = heap.peek() {
127 earliest = earliest.min(top.deadline);
128 }
129 }
130 t.earliest.store(earliest, Ordering::SeqCst);
131 }
132
133 /// The soonest deadline of a timer that `live` keeps. Timers it
134 /// rejects are dropped on the way.
135 pub(crate) fn next(&self, live: impl Fn(&Timer) -> bool) -> Option<u64> {
136 let mut next = None::<u64>;
137 self.scan(|heap| {
138 while let Some(Reverse(top)) = heap.peek() {
139 if live(top) {
140 next = Some(next.map_or(top.deadline, |n| n.min(top.deadline)));
141 break;
142 }
143 heap.pop();
144 }
145 });
146 next
147 }
148
149 /// Take every timer due at `now`, in (deadline, pid) order.
150 pub(crate) fn take_due(&self, now: u64) -> Vec<Timer> {
151 let mut due = Vec::new();
152 self.scan(|heap| {
153 while heap.peek().is_some_and(|Reverse(top)| top.deadline <= now) {
154 due.extend(heap.pop().map(|Reverse(t)| t));
155 }
156 });
157 due.sort_unstable();
158 due
159 }
160}
161
162#[cfg(all(test, loom))]
163mod loom_models {
164 use super::*;
165 use loom::sync::Arc;
166 use loom::thread;
167
168 fn timer(deadline: u64, pid: i64) -> Timer {
169 Timer {
170 deadline,
171 pid,
172 wait: 1,
173 }
174 }
175
176 /// A thread adds a timer while another fires: either the firing thread
177 /// took it, or the bound still shows it to the next check.
178 #[test]
179 fn add_while_firing() {
180 loom::model(|| {
181 let timers = Arc::new(Timers::new(2));
182 timers.add(0, timer(9, 0));
183 let adder = {
184 let timers = timers.clone();
185 thread::spawn(move || timers.add(1, timer(5, 1)))
186 };
187 let taken = timers.firing().take_due(5);
188 adder.join().unwrap();
189 if !taken.iter().any(|t| t.pid == 1) {
190 assert!(timers.maybe_due(5), "a due timer left unseen");
191 }
192 assert!(!timers.maybe_due(4), "the bound goes no lower than a timer");
193 });
194 }
195
196 /// Two threads add while a third looks for the next deadline: the bound
197 /// ends at most at the soonest timer left.
198 #[test]
199 fn adds_while_scanning() {
200 loom::model(|| {
201 let timers = Arc::new(Timers::new(2));
202 let adders: Vec<_> = [(0, 7), (1, 3)]
203 .into_iter()
204 .map(|(heap, deadline)| {
205 let timers = timers.clone();
206 thread::spawn(move || timers.add(heap, timer(deadline, heap as i64)))
207 })
208 .collect();
209 let _ = timers.firing().next(|_| true);
210 for adder in adders {
211 adder.join().unwrap();
212 }
213 assert!(timers.maybe_due(3), "a timer left unseen");
214 });
215 }
216}
217
218#[cfg(all(test, not(loom)))]
219mod tests {
220 use super::*;
221
222 fn timer(deadline: u64, pid: i64, wait: u64) -> Timer {
223 Timer {
224 deadline,
225 pid,
226 wait,
227 }
228 }
229
230 #[test]
231 fn due_timers_come_out_in_deadline_then_pid_order() {
232 let timers = Timers::new(3);
233 timers.add(2, timer(10, 4, 1));
234 timers.add(0, timer(10, 1, 1));
235 timers.add(1, timer(5, 9, 1));
236 timers.add(1, timer(10, 2, 1));
237 timers.add(0, timer(20, 3, 1));
238 assert!(timers.maybe_due(5) && !timers.maybe_due(4));
239 let due = timers.firing().take_due(10);
240 let pids: Vec<i64> = due.iter().map(|t| t.pid).collect();
241 assert_eq!(pids, [9, 1, 2, 4]);
242 assert!(!timers.maybe_due(19) && timers.maybe_due(20));
243 }
244
245 #[test]
246 fn next_skips_and_drops_ended_waits() {
247 let timers = Timers::new(2);
248 timers.add(0, timer(3, 1, 1));
249 timers.add(1, timer(4, 2, 1));
250 timers.add(1, timer(8, 3, 1));
251 let firing = timers.firing();
252 assert_eq!(firing.next(|t| t.pid == 3), Some(8));
253 // The ended ones are gone, and the bound follows.
254 assert_eq!(firing.next(|_| true), Some(8));
255 drop(firing);
256 assert!(!timers.maybe_due(7));
257 assert_eq!(timers.firing().take_due(100).len(), 1);
258 assert_eq!(timers.firing().next(|_| true), None);
259 assert!(!timers.maybe_due(u64::MAX - 1));
260 }
261
262 #[test]
263 fn one_thread_fires_at_a_time() {
264 let timers = Timers::new(1);
265 let firing = timers.firing();
266 assert!(timers.try_firing().is_none());
267 drop(firing);
268 assert!(timers.try_firing().is_some());
269 }
270}