Skip to main content

reifydb_runtime/sync/condvar/
mod.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4//! Condvar synchronization primitive.
5
6use std::time::Duration;
7
8use cfg_if::cfg_if;
9
10use crate::sync::mutex::MutexGuard;
11
12#[cfg(reifydb_target = "native")]
13pub mod native;
14#[cfg(reifydb_target = "wasm")]
15pub mod wasm;
16
17cfg_if! {
18	if #[cfg(reifydb_target = "native")] {
19		type CondvarInner = native::CondvarInner;
20	} else {
21		type CondvarInner = wasm::CondvarInner;
22	}
23}
24
25/// Result of a timed wait on a condition variable.
26pub struct WaitTimeoutResult {
27	timed_out: bool,
28}
29
30impl WaitTimeoutResult {
31	/// Returns whether the wait timed out.
32	#[inline]
33	pub fn timed_out(&self) -> bool {
34		self.timed_out
35	}
36}
37
38/// A condition variable for coordinating threads.
39#[derive(Debug)]
40pub struct Condvar {
41	inner: CondvarInner,
42}
43
44impl Condvar {
45	/// Creates a new condition variable.
46	#[inline]
47	pub fn new() -> Self {
48		Self {
49			inner: CondvarInner::new(),
50		}
51	}
52
53	/// Blocks the current thread until notified.
54	#[inline]
55	pub fn wait<'a, T>(&self, guard: &mut MutexGuard<'a, T>) {
56		self.inner.wait(guard);
57	}
58
59	/// Blocks the current thread until notified or the timeout expires.
60	#[inline]
61	pub fn wait_for<'a, T>(&self, guard: &mut MutexGuard<'a, T>, timeout: Duration) -> WaitTimeoutResult {
62		let timed_out = self.inner.wait_for(guard, timeout);
63		WaitTimeoutResult {
64			timed_out,
65		}
66	}
67
68	/// Wakes up one blocked thread.
69	#[inline]
70	pub fn notify_one(&self) {
71		self.inner.notify_one();
72	}
73
74	/// Wakes up all blocked threads.
75	#[inline]
76	pub fn notify_all(&self) {
77		self.inner.notify_all();
78	}
79}
80
81impl Default for Condvar {
82	#[inline]
83	fn default() -> Self {
84		Self::new()
85	}
86}