Skip to main content

fedimint_core/task/
waiter.rs

1//! Wait for a task to finish.
2
3use tokio::sync::Semaphore;
4
5/// Helper to wait for actions to be [`Self::done`]
6#[derive(Debug)]
7pub struct Waiter {
8    done_semaphore: Semaphore,
9}
10
11impl Default for Waiter {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17impl Waiter {
18    pub fn new() -> Self {
19        Self {
20            // semaphore never has permits.
21            done_semaphore: Semaphore::new(0),
22        }
23    }
24
25    /// Mark this waiter as done.
26    ///
27    /// NOTE: Calling this twice is ignored.
28    pub fn done(&self) {
29        // close the semaphore and notify all waiters.
30        self.done_semaphore.close();
31    }
32
33    /// Wait for [`Self::done`] call.
34    pub async fn wait(&self) {
35        // wait for semaphore to be closed.
36        self.done_semaphore
37            .acquire()
38            .await
39            .expect_err("done semaphore is only closed, never has permits");
40    }
41
42    /// Check if Waiter was marked as done.
43    pub fn is_done(&self) -> bool {
44        self.done_semaphore.is_closed()
45    }
46}
47
48#[cfg(test)]
49mod tests;