use super::{MutexGuard, gate::Gate, wait::Wait};
use crate::{Result, SuspensionReason};
pub struct Condvar {
gate: Gate,
}
impl Condvar {
pub fn new() -> Self {
Self::with_wait_capacity(super::DEFAULT_WAIT_CAPACITY)
.expect("default waiter capacity is positive")
}
pub fn with_wait_capacity(wait_capacity: usize) -> Result<Self> {
Ok(Self {
gate: Gate::new(0, 0, wait_capacity)?,
})
}
pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> Result<MutexGuard<'a, T>> {
let wait = Wait::enter(SuspensionReason::Condvar)?;
let ticket = self.gate.subscribe()?;
let mutex = guard.mutex;
drop(guard);
ticket.wait(&wait)?;
mutex.lock()
}
pub fn notify_one(&self) {
self.gate.signal();
}
pub fn notify_all(&self) {
self.gate.broadcast();
}
pub fn close(&self) {
self.gate.close();
}
pub fn waiting(&self) -> usize {
self.gate.waiting()
}
pub fn wait_capacity(&self) -> usize {
self.gate.wait_capacity()
}
}
impl Default for Condvar {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[path = "condvar_test.rs"]
mod condvar_test;