hpx::condition_variable

hpx::condition_variable#

Defined in header hpx/condition_variable.hpp.

See Public API for a list of names and headers that are part of the public HPX API.

See also:

class condition_variable#

The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable.

The thread that intends to modify the shared variable has to

  1. acquire a hpx::mutex (typically via std::lock_guard)

  2. perform the modification while the lock is held

  3. execute notify_one or notify_all on the condition_variable (the lock does not need to be held for notification)

Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread. Any thread that intends to wait on condition_variable has to

  1. acquire a std::unique_lock<hpx::mutex>, on the same mutex as used to protect the shared variable

  2. either

    1. check the condition, in case it was already updated and notified

    2. execute wait, await_for, or wait_until. The wait operations atomically release the mutex and suspend the execution of the thread.

    3. When the condition variable is notified, a timeout expires, or a spurious wakeup occurs, the thread is awakened, and the mutex is atomically reacquired. The thread should then check the condition and resume waiting if the wake-up was spurious. or

    1. use the predicated overload of wait, wait_for, and wait_until, which takes care of the three steps above.

hpx::condition_variable works only with std::unique_lock<hpx::mutex>. This restriction allows for maximal efficiency on some platforms. hpx::condition_variable_any provides a condition variable that works with any BasicLockable object, such as std::shared_lock.

Condition variables permit concurrent invocation of the wait, wait_for, wait_until, notify_one and notify_all member functions.

The class hpx::condition_variable is a StandardLayoutType. It is not CopyConstructible, MoveConstructible, CopyAssignable, or MoveAssignable.