Skip to main content

mln_engine/exec/
queue.rs

1//! The work of a thread that owns some state: a [`Queue`] of tasks that take
2//! the state by `&mut`, posted from any thread and run by the owning thread
3//! in its turns.
4//!
5//! A task can be posted to run as soon as the owner runs the queue, or once
6//! a deadline passes, and a timed task can be cancelled until it runs. A
7//! thread of its own runs the queue with [`Queue::run`], which parks until a
8//! task arrives or the next deadline passes. A host that has its own loop,
9//! such as the browser's pump, runs it with [`Queue::run_once`] instead, and
10//! learns of new work through the queue's waker.
11
12use std::cmp::Reverse;
13use std::collections::{BinaryHeap, VecDeque};
14use std::sync::{Arc, Weak};
15use std::time::Duration;
16
17use mln_style::hash::HashMap;
18use mln_style::time::Instant;
19use parking_lot::{Condvar, Mutex};
20
21/// A task that runs with the queue's state.
22type Task<S> = Box<dyn FnOnce(&mut S) + Send>;
23
24/// What a queue calls, on the posting thread, when work arrives.
25pub type Waker = Arc<dyn Fn() + Send + Sync>;
26
27/// How many cancelled deadlines the heap keeps, beyond one per waiting timed
28/// task, before it drops them all.
29const CANCELLED_SLACK: usize = 64;
30
31/// A queue of tasks that take `&mut S`, which the thread that runs the queue
32/// owns. Cheap to clone: clones are handles to the same queue.
33///
34/// Tasks run in the order they were posted, and a timed task once its
35/// deadline passed, before the tasks of the same turn. A task that a closed
36/// queue gets drops at once, so tasks that hold handles to their own queue
37/// can't keep it alive once its owner closed it.
38pub struct Queue<S> {
39    inner: Arc<Inner<S>>,
40}
41
42/// A handle to a [`Queue`] that doesn't keep it alive: what it posts once
43/// the queue is gone drops.
44pub struct WeakQueue<S> {
45    inner: Weak<Inner<S>>,
46}
47
48/// Names a timed task of a [`Queue`], for [`Queue::cancel`]. Each one that
49/// a queue hands out names a task of its own, if any: a timed task that a
50/// closed queue got, or whose deadline never comes, has a key that names
51/// nothing.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub struct TimedTask(u64);
54
55struct Inner<S> {
56    state: Mutex<State<S>>,
57    /// Signalled when a task arrives or the queue is woken, or a timed task
58    /// is cancelled.
59    signal: Condvar,
60    waker: Mutex<Option<Waker>>,
61}
62
63struct State<S> {
64    tasks: VecDeque<Entry<S>>,
65    /// The timed tasks that wait, by key.
66    timed: HashMap<u64, Task<S>>,
67    /// The deadlines of the timed tasks, earliest first, and of those due
68    /// at once, the first posted first. A cancelled task's deadline stays
69    /// until it reaches the top, or until the deadlines number more than
70    /// twice the waiting tasks plus [`CANCELLED_SLACK`].
71    deadlines: BinaryHeap<Reverse<(Instant, u64)>>,
72    /// Counts the timed tasks, for their keys.
73    posted: u64,
74    /// A task arrived or the queue was woken since the owner last parked.
75    signalled: bool,
76    /// A stop task ran since the last [`Queue::run`] began.
77    stopped: bool,
78    closed: bool,
79}
80
81enum Entry<S> {
82    Task(Task<S>),
83    Stop,
84}
85
86impl<S> State<S> {
87    /// The deadline and key of the earliest timed task that waits, after
88    /// dropping the cancelled deadlines before it.
89    fn next_timed(&mut self) -> Option<(Instant, u64)> {
90        while let Some(&Reverse((deadline, key))) = self.deadlines.peek() {
91            if self.timed.contains_key(&key) {
92                return Some((deadline, key));
93            }
94            self.deadlines.pop();
95        }
96        None
97    }
98
99    /// Takes the earliest timed task whose deadline is `now` or before.
100    fn take_due(&mut self, now: Instant) -> Option<Task<S>> {
101        let (deadline, key) = self.next_timed()?;
102        if deadline > now {
103            return None;
104        }
105        self.deadlines.pop();
106        self.timed.remove(&key)
107    }
108}
109
110impl<S> Clone for Queue<S> {
111    fn clone(&self) -> Self {
112        Queue { inner: Arc::clone(&self.inner) }
113    }
114}
115
116impl<S> Clone for WeakQueue<S> {
117    fn clone(&self) -> Self {
118        WeakQueue { inner: Weak::clone(&self.inner) }
119    }
120}
121
122impl<S> Default for Queue<S> {
123    fn default() -> Self {
124        Self::new()
125    }
126}
127
128impl<S> Queue<S> {
129    #[must_use]
130    pub fn new() -> Self {
131        Queue {
132            inner: Arc::new(Inner {
133                state: Mutex::new(State {
134                    tasks: VecDeque::new(),
135                    timed: HashMap::default(),
136                    deadlines: BinaryHeap::new(),
137                    posted: 0,
138                    signalled: false,
139                    stopped: false,
140                    closed: false,
141                }),
142                signal: Condvar::new(),
143                waker: Mutex::new(None),
144            }),
145        }
146    }
147
148    /// Runs `task` on the queue's thread, after the tasks posted before it.
149    pub fn post(&self, task: impl FnOnce(&mut S) + Send + 'static) {
150        self.inner.push(Entry::Task(Box::new(task)));
151    }
152
153    /// Runs `task` on the queue's thread in its first turn once `deadline`
154    /// passed, before the turn's other tasks, unless it's
155    /// [`cancel`](Self::cancel)led first.
156    pub fn post_at(&self, deadline: Instant, task: impl FnOnce(&mut S) + Send + 'static) -> TimedTask {
157        let mut state = self.inner.state.lock();
158        let key = state.posted;
159        state.posted += 1;
160        if state.closed {
161            drop(state);
162            drop(task);
163            return TimedTask(key);
164        }
165        state.timed.insert(key, Box::new(task));
166        state.deadlines.push(Reverse((deadline, key)));
167        drop(state);
168        self.wake();
169        TimedTask(key)
170    }
171
172    /// [`post_at`](Self::post_at) `delay` from now. A delay past what an
173    /// `Instant` can hold never comes.
174    pub fn post_after(&self, delay: Duration, task: impl FnOnce(&mut S) + Send + 'static) -> TimedTask {
175        if let Some(deadline) = Instant::now().checked_add(delay) {
176            return self.post_at(deadline, task);
177        }
178        let mut state = self.inner.state.lock();
179        state.posted += 1;
180        TimedTask(state.posted - 1)
181    }
182
183    /// Drops the timed task that `task` names, on this thread, unless it
184    /// has begun to run or dropped already: it never runs, and from now on
185    /// [`next_deadline`](Self::next_deadline) and the queue's parking no
186    /// longer wait for it. A host that armed a timeout for its deadline
187    /// before still sees that timeout end.
188    pub fn cancel(&self, task: TimedTask) {
189        let cancelled = {
190            let mut state = self.inner.state.lock();
191            let cancelled = state.timed.remove(&task.0);
192            if state.deadlines.len() > 2 * state.timed.len() + CANCELLED_SLACK {
193                let State { timed, deadlines, .. } = &mut *state;
194                deadlines.retain(|Reverse((_, key))| timed.contains_key(key));
195            }
196            cancelled
197        };
198        if cancelled.is_some() {
199            // A thread that parks until the task's deadline waits for the
200            // next one instead.
201            self.inner.signal.notify_all();
202        }
203        // Outside the lock: a task's drop may post to the queue.
204        drop(cancelled);
205    }
206
207    /// Calls `waker`, from the posting thread, whenever a task arrives or
208    /// the queue is woken, so that a host that runs the queue with
209    /// [`run_once`](Self::run_once) knows to run it. A timed task calls it
210    /// when it's posted, not when its deadline passes.
211    pub fn set_waker(&self, waker: Option<Waker>) {
212        *self.inner.waker.lock() = waker;
213    }
214
215    /// Wakes the queue's thread, as a task would.
216    pub fn wake(&self) {
217        self.inner.wake();
218    }
219
220    /// Runs the timed tasks whose deadline passed, then the tasks waiting
221    /// now and those they post, with `state`, until none waits. Returns
222    /// whether any task ran.
223    pub fn run_once(&self, state: &mut S) -> bool {
224        self.run_once_by(state, Instant::now())
225    }
226
227    /// [`run_once`](Self::run_once), with the timed tasks whose deadline is
228    /// `now` or before taken as passed, whatever the time is: for a caller
229    /// that keeps time by a clock of its own, such as the benchmarks'
230    /// simulated network, whose deadlines it gives by that clock too.
231    #[cfg(any(test, feature = "bench"))]
232    #[doc(hidden)]
233    pub fn run_once_at(&self, state: &mut S, now: Instant) -> bool {
234        self.run_once_by(state, now)
235    }
236
237    fn run_once_by(&self, state: &mut S, now: Instant) -> bool {
238        let mut ran = false;
239        loop {
240            let task = {
241                let mut queue = self.inner.state.lock();
242                if queue.closed {
243                    return ran;
244                }
245                queue.take_due(now)
246            };
247            let Some(task) = task else { break };
248            task(state);
249            ran = true;
250        }
251        loop {
252            let entry = {
253                let mut queue = self.inner.state.lock();
254                if queue.closed {
255                    return ran;
256                }
257                queue.tasks.pop_front()
258            };
259            match entry {
260                Some(Entry::Task(task)) => task(state),
261                Some(Entry::Stop) => self.inner.state.lock().stopped = true,
262                None => return ran,
263            }
264            ran = true;
265        }
266    }
267
268    /// Whether a task waits for [`run_once`](Self::run_once), or a timed
269    /// task's deadline passed.
270    #[must_use]
271    pub fn has_pending(&self) -> bool {
272        let mut state = self.inner.state.lock();
273        !state.tasks.is_empty() || state.next_timed().is_some_and(|(deadline, _)| deadline <= Instant::now())
274    }
275
276    /// The deadline of the earliest timed task that waits, which a
277    /// cancelled one no longer does.
278    #[must_use]
279    pub fn next_deadline(&self) -> Option<Instant> {
280        self.inner.state.lock().next_timed().map(|(deadline, _)| deadline)
281    }
282
283    /// Sleeps until a task arrives or the queue is woken, or the next timed
284    /// task is due. It returns at once when that happened since it last
285    /// returned, as while the queue was running.
286    pub fn park(&self) {
287        self.park_until(None);
288    }
289
290    /// [`park`](Self::park), but returns at `deadline` at the latest.
291    pub fn park_until(&self, deadline: Option<Instant>) {
292        let mut state = self.inner.state.lock();
293        while !state.signalled {
294            // Again after each wait: a cancel may have taken the earliest.
295            let deadline = match (deadline, state.next_timed().map(|(deadline, _)| deadline)) {
296                (Some(a), Some(b)) => Some(a.min(b)),
297                (a, b) => a.or(b),
298            };
299            match deadline {
300                Some(deadline) => {
301                    let now = Instant::now();
302                    if now >= deadline {
303                        return;
304                    }
305                    self.inner.signal.wait_for(&mut state, deadline - now);
306                }
307                None => self.inner.signal.wait(&mut state),
308            }
309        }
310        state.signalled = false;
311    }
312
313    /// Runs the queue with `state` on this thread until a stop task runs,
314    /// parking while it has nothing to do: what a thread of its own does.
315    pub fn run(&self, state: &mut S) {
316        self.run_with(state, |_| {});
317    }
318
319    /// [`run`](Self::run), and `each_turn` after each turn, before the
320    /// queue parks, for an owner with work of its own on this thread, which
321    /// wakes the queue when it has some.
322    pub fn run_with(&self, state: &mut S, mut each_turn: impl FnMut(&mut S)) {
323        self.inner.state.lock().stopped = false;
324        loop {
325            self.run_once(state);
326            each_turn(state);
327            if self.is_stopped() {
328                return;
329            }
330            self.park();
331        }
332    }
333
334    /// Ends the [`run`](Self::run) in progress, or the next one, at the end
335    /// of the turn that runs this stop task: once the tasks posted before it
336    /// ran, and those that wait in the same turn after it.
337    pub fn stop(&self) {
338        self.inner.push(Entry::Stop);
339    }
340
341    /// Whether a stop task ran since the last [`run`](Self::run) began, for
342    /// a host that runs the queue with [`run_once`](Self::run_once).
343    #[must_use]
344    pub fn is_stopped(&self) -> bool {
345        self.inner.state.lock().stopped
346    }
347
348    /// Drops the tasks that wait, and from now on every task posted, for an
349    /// owner that runs the queue no more.
350    pub fn close(&self) {
351        let (tasks, timed) = {
352            let mut state = self.inner.state.lock();
353            state.closed = true;
354            state.deadlines.clear();
355            (std::mem::take(&mut state.tasks), std::mem::take(&mut state.timed))
356        };
357        // Outside the lock: a task's drop may post to the queue.
358        drop(tasks);
359        drop(timed);
360    }
361
362    /// A handle that doesn't keep the queue alive.
363    #[must_use]
364    pub fn downgrade(&self) -> WeakQueue<S> {
365        WeakQueue { inner: Arc::downgrade(&self.inner) }
366    }
367}
368
369impl<S> WeakQueue<S> {
370    /// The queue, unless it's gone.
371    #[must_use]
372    pub fn upgrade(&self) -> Option<Queue<S>> {
373        self.inner.upgrade().map(|inner| Queue { inner })
374    }
375}
376
377impl<S> Inner<S> {
378    fn push(&self, entry: Entry<S>) {
379        let mut state = self.state.lock();
380        if state.closed {
381            drop(state);
382            drop(entry);
383            return;
384        }
385        state.tasks.push_back(entry);
386        drop(state);
387        self.wake();
388    }
389
390    fn wake(&self) {
391        self.state.lock().signalled = true;
392        self.signal.notify_all();
393        let waker = self.waker.lock().clone();
394        if let Some(waker) = waker {
395            waker();
396        }
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use std::sync::atomic::{AtomicUsize, Ordering};
403
404    use super::*;
405
406    #[test]
407    fn tasks_run_in_order_with_the_state() {
408        let queue = Queue::<Vec<u32>>::new();
409        for i in 0..5 {
410            queue.post(move |state| state.push(i));
411        }
412        let mut state = Vec::new();
413        assert!(queue.run_once(&mut state));
414        assert_eq!(state, [0, 1, 2, 3, 4]);
415        assert!(!queue.run_once(&mut state));
416    }
417
418    #[test]
419    fn a_task_posted_by_a_task_runs_in_the_same_turn() {
420        let queue = Queue::<u32>::new();
421        let again = queue.clone();
422        queue.post(move |count| {
423            *count += 1;
424            again.post(|count| *count += 1);
425        });
426        let mut count = 0;
427        queue.run_once(&mut count);
428        assert_eq!(count, 2);
429    }
430
431    #[test]
432    fn timed_tasks_run_once_due_earliest_first_before_the_turns_tasks() {
433        let queue = Queue::<Vec<&str>>::new();
434        let now = Instant::now();
435        let later = now + Duration::from_secs(3600);
436        queue.post_at(later, |state| state.push("later"));
437        queue.post_at(now, |state| state.push("due"));
438        queue.post_at(now, |state| state.push("due too"));
439        queue.post(|state| state.push("task"));
440        let mut state = Vec::new();
441        queue.run_once(&mut state);
442        assert_eq!(state, ["due", "due too", "task"]);
443        assert_eq!(queue.next_deadline(), Some(later));
444        let soon = Instant::now() + Duration::from_millis(20);
445        queue.post_at(soon, |state| state.push("soon"));
446        queue.park();
447        // The posts signalled the queue, so the first park returns at once.
448        queue.park();
449        assert!(Instant::now() >= soon);
450        queue.run_once(&mut state);
451        assert_eq!(state, ["due", "due too", "task", "soon"]);
452        assert_eq!(queue.next_deadline(), Some(later));
453    }
454
455    #[test]
456    fn a_cancelled_timed_task_drops_and_never_runs() {
457        struct Counted(Arc<AtomicUsize>);
458        impl Drop for Counted {
459            fn drop(&mut self) {
460                self.0.fetch_add(1, Ordering::SeqCst);
461            }
462        }
463        let dropped = Arc::new(AtomicUsize::new(0));
464        let queue = Queue::<Vec<&str>>::new();
465        let now = Instant::now();
466        let counted = Counted(Arc::clone(&dropped));
467        let cancelled = queue.post_at(now, move |state| {
468            drop(counted);
469            state.push("cancelled");
470        });
471        let kept = queue.post_at(now, |state| state.push("kept"));
472        queue.cancel(cancelled);
473        assert_eq!(dropped.load(Ordering::SeqCst), 1, "the cancel drops the task");
474        let mut state = Vec::new();
475        queue.run_once(&mut state);
476        assert_eq!(state, ["kept"]);
477        // A key whose task ran, or that was cancelled, names nothing.
478        queue.cancel(kept);
479        queue.cancel(cancelled);
480        assert!(!queue.run_once(&mut state));
481    }
482
483    #[test]
484    fn next_deadline_and_park_skip_cancelled_tasks() {
485        let queue = Queue::<()>::new();
486        let now = Instant::now();
487        let soon = queue.post_at(now + Duration::from_millis(5), |()| {});
488        let later = now + Duration::from_secs(60);
489        queue.post_at(later, |()| {});
490        assert_eq!(queue.next_deadline(), Some(now + Duration::from_millis(5)));
491        queue.cancel(soon);
492        assert_eq!(queue.next_deadline(), Some(later));
493        assert!(!queue.has_pending());
494        // The posts signalled the queue; the second park waits for the
495        // cancelled task's deadline no more, only for the bound.
496        queue.park();
497        let bound = Instant::now() + Duration::from_millis(30);
498        queue.park_until(Some(bound));
499        assert!(Instant::now() >= bound);
500        assert!(!queue.run_once(&mut ()));
501    }
502
503    /// A parked thread whose earliest timed task is cancelled waits for the
504    /// next one instead.
505    #[test]
506    fn a_cancel_moves_a_parked_threads_deadline() {
507        let queue = Queue::<()>::new();
508        let now = Instant::now();
509        let due = now + Duration::from_millis(100);
510        let bound = now + Duration::from_millis(150);
511        let first = queue.post_at(due, |()| {});
512        let parked = queue.clone();
513        let thread = std::thread::spawn(move || {
514            // The post signalled the queue, so the first park returns at once.
515            parked.park();
516            parked.park_until(Some(bound));
517            Instant::now()
518        });
519        std::thread::sleep(Duration::from_millis(10));
520        queue.cancel(first);
521        // A busy machine can keep this thread from cancelling until after
522        // the task fell due, and then the parked thread rightly returns at
523        // its deadline. Only a cancel that ends before it moves the deadline.
524        let cancelled_in_time = Instant::now() < due;
525        let returned = thread.join().unwrap();
526        assert!(returned >= if cancelled_in_time { bound } else { due });
527    }
528
529    #[test]
530    fn cancelled_deadlines_stay_bounded_by_the_waiting_tasks() {
531        let queue = Queue::<()>::new();
532        let far = Instant::now() + Duration::from_secs(3600);
533        let kept: Vec<_> = (0..10).map(|_| queue.post_at(far, |()| {})).collect();
534        for _ in 0..10_000 {
535            let task = queue.post_at(far, |()| {});
536            queue.cancel(task);
537        }
538        let state = queue.inner.state.lock();
539        assert_eq!(state.timed.len(), kept.len());
540        assert!(state.deadlines.len() <= 2 * kept.len() + CANCELLED_SLACK + 1);
541    }
542
543    #[test]
544    fn run_returns_after_the_turn_of_its_stop_and_runs_again() {
545        let queue = Queue::<u32>::new();
546        queue.post(|count| *count += 1);
547        queue.stop();
548        queue.post(|count| *count += 10);
549        let mut count = 0;
550        queue.run(&mut count);
551        assert_eq!(count, 11);
552        assert!(queue.is_stopped());
553        queue.stop();
554        queue.post(|count| *count += 100);
555        queue.run(&mut count);
556        assert_eq!(count, 111);
557    }
558
559    #[test]
560    fn run_from_another_thread_waits_for_its_tasks() {
561        let queue = Queue::<u32>::new();
562        let handle = queue.clone();
563        let thread = std::thread::spawn(move || {
564            let mut count = 0;
565            handle.run(&mut count);
566            count
567        });
568        for _ in 0..10 {
569            queue.post(|count| *count += 1);
570        }
571        queue.post_after(Duration::from_millis(5), |count| *count += 100);
572        queue.post_after(Duration::from_millis(10), |_| {});
573        let stop = queue.clone();
574        queue.post_after(Duration::from_millis(10), move |_| stop.stop());
575        assert_eq!(thread.join().unwrap(), 110);
576    }
577
578    #[test]
579    fn a_closed_queue_drops_what_waits_and_what_comes() {
580        struct Counted(Arc<AtomicUsize>);
581        impl Drop for Counted {
582            fn drop(&mut self) {
583                self.0.fetch_add(1, Ordering::SeqCst);
584            }
585        }
586        let dropped = Arc::new(AtomicUsize::new(0));
587        let queue = Queue::<()>::new();
588        let (waiting, timed) = (Counted(Arc::clone(&dropped)), Counted(Arc::clone(&dropped)));
589        // Each task holds a handle to its own queue.
590        let own = queue.clone();
591        queue.post(move |()| drop((waiting, own)));
592        queue.post_after(Duration::from_secs(60), move |()| drop(timed));
593        queue.close();
594        assert_eq!(dropped.load(Ordering::SeqCst), 2);
595        let late = Counted(Arc::clone(&dropped));
596        queue.post(move |()| drop(late));
597        assert_eq!(dropped.load(Ordering::SeqCst), 3);
598        assert!(!queue.run_once(&mut ()));
599        let weak = queue.downgrade();
600        drop(queue);
601        assert!(weak.upgrade().is_none());
602    }
603
604    #[test]
605    fn the_waker_hears_of_posts_and_wakes() {
606        let woken = Arc::new(AtomicUsize::new(0));
607        let queue = Queue::<()>::new();
608        let counter = Arc::clone(&woken);
609        queue.set_waker(Some(Arc::new(move || {
610            counter.fetch_add(1, Ordering::SeqCst);
611        })));
612        queue.post(|()| {});
613        queue.wake();
614        queue.post_after(Duration::from_secs(60), |()| {});
615        assert_eq!(woken.load(Ordering::SeqCst), 3);
616        assert!(queue.has_pending());
617        queue.run_once(&mut ());
618        assert!(!queue.has_pending());
619    }
620}