Skip to main content

Condvar

Type Alias Condvar 

Source
pub type Condvar = Condvar<RawCondvar>;
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 thread must block.

Note that this module places one additional restriction over the system condition variables: each condvar can be used with only one mutex at a time. Any attempt to use multiple mutexes on the same condition variable simultaneously will result in a runtime panic. However it is possible to switch to a different mutex if there are no threads currently waiting on the condition variable.

§Differences from the standard library Condvar

  • No spurious wakeups: A wait will only return a non-timeout result if it was woken up by notify_one or notify_all.
  • notify_one returns exactly whether a waiting thread was notified, and notify_all returns the exact number of waiting threads notified.
  • Condvar::notify_all requeues waiters directly onto the associated Mutex and wakes them as the lock becomes available, avoiding a thundering herd.

§Examples

use parking_lot::{Mutex, Condvar};
use std::sync::Arc;
use std::thread;

let pair = Arc::new((Mutex::new(false), Condvar::new()));
let pair2 = pair.clone();

// Inside of our lock, spawn a new thread, and then wait for it to start
thread::spawn(move|| {
    let &(ref lock, ref cvar) = &*pair2;
    let mut started = lock.lock();
    *started = true;
    cvar.notify_one();
});

// wait for the thread to start up
let &(ref lock, ref cvar) = &*pair;
let mut started = lock.lock();
if !*started {
    cvar.wait(&mut started);
}
// In this single-waiter example an `if` is sufficient because
// parking_lot's Condvar never spuriously wakes: wait() only returns after
// notify_one or notify_all is called. Code with multiple waiters or multiple
// predicates may still need a loop to re-check the predicate.

Aliased Type§

pub struct Condvar { /* private fields */ }