Condition variables
Condition variables are another synchronization primitive provided by the C++ Standard Library. They allow multiple threads to communicate with each other. They also allow for several threads to wait for a notification from another thread. Condition variables are always associated with a mutex.
In the following example, a thread must wait for a counter to be equal to a certain value:
#include <chrono> #include <condition_variable> #include <iostream> #include <mutex> #include <thread> #include <vector> int counter = 0; int main() { Â Â Â Â using namespace std::chrono_literals; Â Â Â Â std::mutex mtx; Â Â Â Â std::mutex cout_mtx; Â Â Â Â std::condition_variable cv; Â Â Â Â auto increment_counter = [&] { Â Â Â Â Â Â Â Â for (int i = 0; i < 20; ++i) { Â Â Â Â Â Â Â Â Â &...