Skip to main content

ferrijs_std/utils/
latch.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5use tokio::sync::Notify;
6
7#[derive(Default)]
8pub struct Latch {
9    count: AtomicUsize,
10    notify: Notify,
11}
12
13impl Latch {
14    pub fn increment(&self) {
15        self.count.fetch_add(1, Ordering::Relaxed);
16    }
17
18    pub fn decrement(&self) {
19        let previous = self.count.fetch_sub(1, Ordering::Relaxed);
20        if previous == 1 {
21            self.notify.notify_waiters();
22        }
23    }
24
25    pub async fn wait(&self) {
26        if self.count.load(Ordering::Relaxed) > 0 {
27            self.notify.notified().await;
28        }
29    }
30}