Documentation Home >> Headers >> <condition_variable> Header >> std::condition_variable_any >> std::condition_variable_any::wait_for Member function

Wait until the std::condition_variable_any is notified by a call to notify_one() or notify_all(), or until a specified time period has elapsed or the thread is woken spuriously.

template<typename Lockable,typename Rep,
    typename Period>
std::cv_status wait_for(
    Lockable& lock,
    std::chrono::duration<Rep,Period> const&
    relative_time);

Preconditions:

Lockable meets the Lockable Requirements, and lock owns a lock.

Effects:

Atomically unlock the supplied lock object and block until the the thread is woken by a call to notify_one() or notify_all() by another thread, or the time period specified by relative_time has elapsed or the thread is woken spuriously. The lock object is locked again before the call to wait_for() returns.

Returns:

std::cv_status::no_timeout if the thread was woken by a call to notify_one() or notify_all() or a spurious wake-up, std::cv_status::timeout otherwise.

Throws:

std::system_error if the effects cannot be achieved. If the lock object is unlocked during the call to wait_for(), it is locked again on exit, even if the function exits via an exception.

Note:

The spurious wake ups mean that a thread calling wait_for() may wake even though no thread has called notify_one() or notify_all(). It is therefore recommended that the overload of wait_for() that takes a predicate is used in preference where possible. Otherwise, it is recommended that wait_for() be called in a loop which tests the predicate associated with the condition variable. Care must be taken when doing this to ensure that the timeout is still valid; wait_until() may be more appropriate in many circumstances. The thread may be blocked for longer than the specified duration. Where possible, the elapsed time is determined by a steady clock.

Synchronization:

Calls to notify_one(), notify_all(), wait(), wait_for() and wait_until() on a single std::condition_variable_any instance are serialized. A call to notify_one() or notify_all() will only wake threads that started waiting prior to that call.

Header

#include <condition_variable>

See Also