Skip to main content

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