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