Namespaces
Variants
Views
Actions

std::condition_variable::wait

From cppreference.com
void wait( std::unique_lock<std::mutex>& lock );
(1) (since C++11)
template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate pred );
(2) (since C++11)

1) Atomically releases lock, blocks the current executing thread, and adds it to the list of threads waiting on *this. The thread will be unblocked when notify_all() or notify_one() is executed. It may also be unblocked spuriously. When unblocked, regardless of the reason, lock is reacquired and wait() exits. If this function exits via exception, lock is also reacquired.

2) Equivalent to while (!pred()) wait(lock);. This overload may be used to ignore spurious awakenings while waiting for a specific condition to become true.

Contents

[edit] Parameters

lock - an object of type std::unique_lock<std::mutex>, which must be locked by the current thread
pred - predicate which returns ​false if the waiting should be continued.

The signature of the predicate function should be equivalent to the following:

bool pred();

[edit] Return value

(none)

[edit] Exceptions

May throw std::system_error, may also propagate exceptions thrown by lock.lock() or lock.unlock().

[edit] Notes

Calling this function if lock.mutex() is not locked by the current thread is undefined behavior.

Calling this function if lock.mutex() is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior.

[edit] Example

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
 
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
 
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, [](){return i == 1;});
    std::cerr << "...finished waiting. i == 1\n";
}
 
void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cerr << "Notifying...\n";
    cv.notify_all();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    i = 1;
    std::cerr << "Notifying again...\n";
    cv.notify_all();
}
 
int main()
{
    std::thread t1(waits), t2(waits), t3(waits), t4(signals);
    t1.join(); t2.join(), t3.join(), t4.join();
}

Output:

Waiting...
Waiting...
Waiting...
Notifying...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

[edit] See also

blocks the current thread until the condition variable
is woken up or after the specified timeout duration
(public member function) [edit]
blocks the current thread until the condition variable
is woken up or until specified time point has been reached
(public member function) [edit]