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. If the buffer is full the function returns it in the error
19    pub fn register(&mut self, w: &Waker) {
20        // If we already have some waker that wakes the same task as `w`, do nothing.
21        // This avoids cloning wakers, and avoids unnecessary mass-wakes.
22        for w2 in &self.wakers {
23            if w.will_wake(w2) {
24                return;
25            }
26        }
27
28        if self.wakers.is_full() {
29            // All waker slots were full. It's a bit inefficient, but we can wake everything.
30            // Any future that is still active will simply reregister.
31            // This won't happen a lot, so it's ok.
32            self.wake();
33        }
34
35        if self.wakers.push(w.clone()).is_err() {
36            // This can't happen unless N=0
37            // (Either `wakers` wasn't full, or it was in which case `wake()` empied it)
38            panic!("tried to push a waker to a zero-length MultiWakerRegistration")
39        }
40    }
41
42    /// Wake all registered wakers. This clears the buffer
43    pub fn wake(&mut self) {
44        // heapless::Vec has no `drain()`, do it unsafely ourselves...
45
46        // First set length to 0, without dropping the contents.
47        // This is necessary for soundness: if wake() panics and we're using panic=unwind.
48        // Setting len=0 upfront ensures other code can't observe the vec in an inconsistent state.
49        // (it'll leak wakers, but that's not UB)
50        let len = self.wakers.len();
51        unsafe { self.wakers.set_len(0) }
52
53        for i in 0..len {
54            // Move a waker out of the vec.
55            let waker = unsafe { self.wakers.as_mut_ptr().add(i).read() };
56            // Wake it by value, which consumes (drops) it.
57            waker.wake();
58        }
59    }
60}