C++ condition_variable::wait() Function
The std::condition_variable::wait() function in C++, is used to block the thread until a specified condition is met. It is used in conjunction with the std::mutex and a std::unique_lock, ensuring the thread-safe execution. When the condition becomes true, the function reacquires the lock and resumes the execution.
Syntax
Following is the syntax for std::condition_variable::wait() function.
void notify_all() noexcept;void wait (unique_lock<mutex>& lck);
or
void wait (unique_lock<mutex>& lck, Predicate pred);
Parameters
- lck − It indicates a unique_lock object whose mutex object is currently locked by this thread.
- pred − It indicates a callable object or function that takes no arguments and returns a value that can be evaluated as a bool.
Return value
This function does not return anything.
Example 1
Let's look at the following example, where we are going to coordinates two threads.
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
std::mutex a;
std::condition_variable b;
bool turn = false;
void x1() {
std::unique_lock < std::mutex > lock(a);
std::cout << "x1 waiting for its turn....\n";
b.wait(lock, [] {
return turn;
});
std::cout << "x1 proceeding...\n";
}
void x2() {
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard < std::mutex > lock(a);
turn = true;
std::cout << "x2 signals Thread 1's turn.\n";
}
b.notify_one();
}
int main() {
std::thread a1(x1);
std::thread a2(x2);
a1.join();
a2.join();
return 0;
}
Output
Output of the above code is as follows −
x1 waiting for its turn....
x2 signals Thread 1's turn.
x1 proceeding...
cpp_condition_variable.htm