pub struct ConditionVariable {
waiters: SpinLock<VecDeque<ParkHandle>>,
}Expand description
A Condition Variable
Condition variables represent the ability to block a thread such that it consumes no CPU time while waiting for an event to occur. Condition variables are typically associated with a boolean predicate (a condition) and a mutex. The predicate is always verified inside of the mutex before determining that a thread must block.
Functions in this module will block the current thread of execution. Note that any attempt to use multiple mutexes on the same condition variable may result in a runtime panic.
Fields§
§waiters: SpinLock<VecDeque<ParkHandle>>Implementations§
Source§impl ConditionVariable
impl ConditionVariable
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new condition variable which is ready to be waited on and signaled.
Sourcepub fn wait_while<'a, T>(
&self,
mutex: &'a Mutex<T>,
predicate: impl Fn(&mut T) -> bool,
) -> MutexGuard<'a, T>
pub fn wait_while<'a, T>( &self, mutex: &'a Mutex<T>, predicate: impl Fn(&mut T) -> bool, ) -> MutexGuard<'a, T>
Blocks the current thread while predicate returns true.
This function takes reference of a Mutex and checks the
predicate. If it returns true, the thread is blocked and the mutex is
temporarily released. When the thread is signaled and wakes up, it
reacquires the mutex and re-evaluates the predicate. This loop continues
until the predicate returns false.
§Example
let guard = condvar.wait_while(&mutex, |state| state.count == 0);There is no need to check the predicate before calling wait_while.
It performs the entire check-and-sleep logic internally.
Sourcepub fn signal<'a, T>(&self, guard: MutexGuard<'a, T>)
pub fn signal<'a, T>(&self, guard: MutexGuard<'a, T>)
Wakes up one blocked thread on this condvar.
If there is a blocked thread on this condition variable, then it will
be woken up from its call to wait_while. Calls to signal are not
buffered in any way.
To wake up all threads, see broadcast.
Sourcepub fn broadcast<'a, T>(&self, guard: MutexGuard<'a, T>)
pub fn broadcast<'a, T>(&self, guard: MutexGuard<'a, T>)
Wakes up all blocked threads on this condvar.
This method will ensure that any current waiters on the condition
variable are awoken. Calls to broadcast() are not buffered in any
way.
To wake up only one thread, see signal.