Wait until the std::condition_variable 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 Rep,typename Period> cv_status wait_for(std::unique_lock<std::mutex>& lock, std::chrono::duration<Rep,Period> const& relative_time);
- Preconditions:
lock.owns_lock()istrue, and the lock is owned by the calling thread.- Effects:
Atomically unlock the supplied
lockobject and block until the the thread is woken by a call tonotify_one()ornotify_all()by another thread, or the time period specified byrelative_timehas elapsed or the thread is woken spuriously. Thelockobject is locked again before the call towait_for()returns.- Returns:
std::cv_status::no_timeoutif the thread was woken by a call tonotify_one()ornotify_all()or a spurious wake-up,std::cv_status::timeoutotherwise.- Throws:
std::system_errorif the effects cannot be achieved. If thelockobject is unlocked during the call towait_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 callednotify_one()ornotify_all(). It is therefore recommended that the overload ofwait_for()that takes a predicate is used in preference where possible. Otherwise, it is recommended thatwait_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 monotonic clock.- Synchronization:
Calls to
notify_one(),notify_all(),wait(),wait_for()andwait_until()on a singlestd::condition_variableinstance are serialized. A call tonotify_one()ornotify_all()will only wake threads that started waiting prior to that call.
Header
#include <condition_variable>