Documentation Home >> Headers >> <condition_variable> Header >> std::condition_variable_any >> std::condition_variable_any::wait_for Member function overload that takes a predicate

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

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

Preconditions:

The expression pred() shall be valid, and shall return a value that is convertible to bool. Lockable meets the Lockable Requirements, and lock owns a lock.

Effects:

As-if

internal_clock::time_point end=internal_clock::now()+relative_time;
while(!pred())
{
    std::chrono::duration<Rep,Period> remaining_time=
        end-internal_clock::now();
    if(wait_for(lock,remaining_time)==
        std::cv_status::timeout)
        return pred();
}
return true;
Returns:

true if the most recent call to pred() returned true, false if the time period specified by relative_time has elapsed, and pred() returned false.

Note:

The potential for spurious wake ups means that it is unspecified how many times pred will be called. pred will always be invoked with the mutex referenced by lock locked, and the function shall return if (and only if) an evaluation of (bool)pred() returns true or the time period specified by relative_time has elapsed. The thread may be blocked for longer than the specified duration. Where possible, the elapsed time is determined by a steady clock.

Throws:

Any exception thrown by a call to pred, or std::system_error if the effects could not be achieved.

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