Namespaces
Variants
Actions

std::condition_variable::wait_for

From cppreference.com
 
 
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
(C++11)
Generic lock management
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
(C++11)
Safe reclamation
(C++26)
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11)(deprecated in C++20)
(C++11)(deprecated in C++20)
Memory ordering
(C++11)(deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
 
 
template< class Rep, class Period >

std::cv_status wait_for( std::unique_lock<std::mutex>& lock,

                         const std::chrono::duration<Rep, Period>& rel_time );
(1) (since C++11)
template< class Rep, class Period, class Predicate >

bool wait_for( std::unique_lock<std::mutex>& lock,
               const std::chrono::duration<Rep, Period>& rel_time,

               Predicate pred );
(2) (since C++11)

wait_for causes the current thread to block until the condition variable is notified, the given duration has been elapsed, or a spurious wakeup occurs. pred can be optionally provided to detect spurious wakeup.

1) Equivalent to return wait_until(lock, std::chrono::steady_clock::now() + rel_time);.
2) Equivalent to return wait_until(lock, std::chrono::steady_clock::now() + rel_time, std::move(pred));.
This overload may be used to ignore spurious awakenings while waiting for a specific condition to become true.

Right after wait_for returns, lock.owns_lock() is true, and lock.mutex() is locked by the calling thread. If these postconditions cannot be satisfied[1], calls std::terminate.

If any of the following conditions is satisfied, the behavior is undefined:

  • lock.owns_lock() is false.
  • lock.mutex() is not locked by the calling thread.
  • If some other threads are also waiting on *this, lock.mutex() is different from the mutex unlocked by the waiting functions (wait, wait_for and wait_until) called on *this by those threads.
  1. This can happen if the re-locking of the mutex throws an exception.

Contents