How do I use condition_variable?

The condition_variable in C++ is used to block one or more threads until another thread notifies them that it can continue. This is useful for coordinating threads and preventing race conditions while sharing data. Below is an example demonstrating its use.

#include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cv; bool ready = false; void print_id(int id) { std::unique_lock<std::mutex> lck(mtx); while (!ready) cv.wait(lck); // wait until ready // After being notified, the thread can proceed std::cout << "Thread " << id << " is proceeding." << std::endl; } void go() { std::unique_lock<std::mutex> lck(mtx); ready = true; cv.notify_all(); // notify all waiting threads } int main() { std::thread threads[10]; for (int i = 0; i < 10; ++i) threads[i] = std::thread(print_id, i); std::cout << "10 threads ready to race..." << std::endl; go(); // Go, notify all threads for (auto &th : threads) th.join(); return 0; }

condition_variable C++ multithreading synchronization thread coordination