Conditional variables are used in multi-threaded applications to "synchronize" threads.
Simply put, one or more threads can wait (block) on a conditional variable. When another threads signals (notifies) that conditional variable, then either all or just one of the "waiting" threads will be unblocked and allowed to go on...
As an aside: Unlike semaphores, a conditional variable does not have a "counter" associated with it. So, if you signal a conditional variable while no thread is currently waiting on that conditional variable, then the signal is simply "lost" (discarded).
The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable. A condition variable is an object able to block the calling thread until notified to resume ++
#include <condition_variable>
#include <iostream>
#include <future>
#include <vector>
#include <mutex>
#include <conio.h>
#include <chrono> // to wait
int main()
{
std::vector<std::future<void>> v;
std::mutex m;
std::condition_variable cv; // condition variable
for (int i = 0; i < 5; ++i)
v.push_back(std::async([&](int n) { std::unique_lock<std::mutex> mx{ m }; cv.wait(mx); std::cout << "Thread " << n << std::endl; }, i + 1));
// threads have been created but waiting the signal ^^^^^^^^^^^
std::cout << "Now you get 5 threads waiting the main signal - the condition_variable" << std::endl;
std::cout << "Press a key to proceed ..." << std::endl;
char c;
c = _getch();
// notify the signal to all thread using the condition variable
cv.notify_all();
// or something else, but you HAVE to wait because of output
std::this_thread::sleep_for(std::chrono::milliseconds(100));
return 0;
}
Now you get 5 threads waiting the main signal - the condition_variable
Thread 4
Thread 3
Thread 1
Thread 5
Thread 2