Skip to main content

mln_engine/exec/
event_queue.rs

1//! A queue of events that producers push and one owner drains.
2//!
3//! Producers on any thread push events. The owner takes them all at once, in
4//! the order they were pushed, when it's ready to handle them. An optional
5//! waker tells the owner that the queue has events again.
6
7use std::sync::Arc;
8
9use parking_lot::Mutex;
10
11/// Tells the owner of a queue that the queue has events to take. It runs on
12/// the thread that pushed the event, so it must not take the events itself
13/// there: it schedules the owner to do it, as by posting to its `Queue`.
14pub type Waker = Arc<dyn Fn() + Send + Sync>;
15
16struct Shared<T> {
17    events: Mutex<Vec<T>>,
18    waker: Mutex<Option<Waker>>,
19}
20
21/// A queue of events. Clones push to and take from the same queue.
22pub struct EventQueue<T> {
23    shared: Arc<Shared<T>>,
24}
25
26impl<T> Clone for EventQueue<T> {
27    fn clone(&self) -> Self {
28        EventQueue { shared: Arc::clone(&self.shared) }
29    }
30}
31
32impl<T> Default for EventQueue<T> {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl<T> EventQueue<T> {
39    #[must_use]
40    pub fn new() -> Self {
41        EventQueue { shared: Arc::new(Shared { events: Mutex::new(Vec::new()), waker: Mutex::new(None) }) }
42    }
43
44    /// Adds `event` at the end of the queue. The waker runs when the queue
45    /// was empty, after the queue is unlocked.
46    pub fn push(&self, event: T) {
47        let was_empty = {
48            let mut events = self.shared.events.lock();
49            events.push(event);
50            events.len() == 1
51        };
52        if was_empty {
53            let waker = self.shared.waker.lock().clone();
54            if let Some(waker) = waker {
55                waker();
56            }
57        }
58    }
59
60    /// Takes every event in the queue, oldest first. The queue keeps its
61    /// buffer for the events pushed next.
62    #[must_use]
63    pub fn take(&self) -> Vec<T> {
64        self.shared.events.lock().drain(..).collect()
65    }
66
67    /// Whether the queue has no events. A push counts once it has queued its
68    /// event, before it runs the waker.
69    #[must_use]
70    pub fn is_empty(&self) -> bool {
71        self.shared.events.lock().is_empty()
72    }
73
74    /// Sets the waker that the queue runs when it gets an event while empty.
75    /// A queue that already has events runs the new waker at once.
76    pub fn set_waker(&self, waker: Option<Waker>) {
77        *self.shared.waker.lock() = waker.clone();
78        if let Some(waker) = waker
79            && !self.is_empty()
80        {
81            waker();
82        }
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use std::sync::atomic::{AtomicUsize, Ordering};
89
90    use super::*;
91
92    #[test]
93    fn takes_events_in_order() {
94        let queue = EventQueue::new();
95        queue.push(1);
96        queue.clone().push(2);
97        assert_eq!(queue.take(), vec![1, 2]);
98        assert!(queue.is_empty());
99    }
100
101    #[test]
102    fn wakes_once_per_batch() {
103        let queue = EventQueue::new();
104        let wakes = Arc::new(AtomicUsize::new(0));
105        let counter = Arc::clone(&wakes);
106        queue.set_waker(Some(Arc::new(move || {
107            counter.fetch_add(1, Ordering::SeqCst);
108        })));
109        queue.push(1);
110        queue.push(2);
111        assert_eq!(wakes.load(Ordering::SeqCst), 1);
112        let _ = queue.take();
113        queue.push(3);
114        assert_eq!(wakes.load(Ordering::SeqCst), 2);
115    }
116
117    #[test]
118    fn a_new_waker_runs_for_queued_events() {
119        let queue = EventQueue::new();
120        queue.push(1);
121        let wakes = Arc::new(AtomicUsize::new(0));
122        let counter = Arc::clone(&wakes);
123        queue.set_waker(Some(Arc::new(move || {
124            counter.fetch_add(1, Ordering::SeqCst);
125        })));
126        assert_eq!(wakes.load(Ordering::SeqCst), 1);
127    }
128}