Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
latch.rs

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