embassy_sync/waitqueue/
multi_waker.rs

1use core::task::Waker;
2
3use heapless::Vec;
4
5/// Utility struct to register and wake multiple wakers.
6/// Queue of wakers with a maximum length of `N`.
7/// Intended for waking multiple tasks.
8pub struct MultiWakerRegistration<const N: usize> {
9    wakers: Vec<Waker, N>,
10}
11
12impl<const N: usize> MultiWakerRegistration<N> {
13    /// Create a new empty instance
14    pub const fn new() -> Self {
15        Self { wakers: Vec::new() }
16    }
17
18    /// Register a waker.
19    ///
20    /// If the buffer is full, [wakes all the wakers](Self::wake), clears its buffer and registers the waker.
21    pub fn register(&mut self, w: &Waker) {
22        // If we already have some waker that wakes the same task as `w`, do nothing.
23        // This avoids cloning wakers, and avoids unnecessary mass-wakes.
24        for w2 in &self.wakers {
25            if w.will_wake(w2) {
26                return;
27            }
28        }
29
30        if self.wakers.is_full() {
31            // All waker slots were full. It's a bit inefficient, but we can wake everything.
32            // Any future that is still active will simply reregister.
33            // This won't happen a lot, so it's ok.
34            self.wake();
35        }
36
37        if self.wakers.push(w.clone()).is_err() {
38            // This can't happen unless N=0
39            // (Either `wakers` wasn't full, or it was in which case `wake()` empied it)
40            panic!("tried to push a waker to a zero-length MultiWakerRegistration")
41        }
42    }
43
44    /// Wake all registered wakers. This clears the buffer
45    pub fn wake(&mut self) {
46        // heapless::Vec has no `drain()`, do it unsafely ourselves...
47
48        // First set length to 0, without dropping the contents.
49        // This is necessary for soundness: if wake() panics and we're using panic=unwind.
50        // Setting len=0 upfront ensures other code can't observe the vec in an inconsistent state.
51        // (it'll leak wakers, but that's not UB)
52        let len = self.wakers.len();
53        unsafe { self.wakers.set_len(0) }
54
55        for i in 0..len {
56            // Move a waker out of the vec.
57            let waker = unsafe { self.wakers.as_mut_ptr().add(i).read() };
58            // Wake it by value, which consumes (drops) it.
59            waker.wake();
60        }
61    }
62}