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) { &...