C++ condition_variable::notify_all() Function



The std::condition_variable::notify_all() function in C++, is a synchronization mechanism used in multithreading. It wakes up all threads waiting on the condition variable, allowing them to recheck the associated condition.

This function is used to when a shared resource state changes, making it ready for multiple waiting threads to proceed.

Syntax

Following is the syntax for std::condition_variable::notify_all() function.

void notify_all() noexcept;

Parameters

This function does not accepts any parameter.

Return value

This function does not return anything.

Example 1

Let's look at the following example, where we are going to consider the basic usage of the notify_all() function.

Open Compiler
#include <iostream> #include <thread> #include <condition_variable> #include <mutex> std::condition_variable a; std::mutex b; bool ready = false; void x(int id) { std::unique_lock < std::mutex > lock(b); a.wait(lock, [] { return ready; }); std::cout << id << " is proceeding.\n"; } int main() { std::thread x1(x, 1); std::thread x2(x, 2); std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard < std::mutex > lock(b); ready = true; } a.notify_all(); x1.join(); x2.join(); return 0; }

Output

Output of the above code is as follows −

2 is proceeding.
1 is proceeding.
cpp_condition_variable.htm
Advertisements