Condition Variables

Thread coordination

Interview Relevant: Producer-consumer

Condition Variables

Coordinate threads waiting for conditions.

Code Examples

Condition variables for thread coordination.

cpp
1#include <condition_variable>
2
3mutex mtx;
4condition_variable cv;
5queue<int> dataQueue;
6bool done = false;
7
8// Producer
9void producer() {
10    for (int i = 0; i < 10; i++) {
11        {
12            lock_guard<mutex> lock(mtx);
13            dataQueue.push(i);
14        }
15        cv.notify_one();  // Wake one waiting thread
16    }
17    {
18        lock_guard<mutex> lock(mtx);
19        done = true;
20    }
21    cv.notify_all();  // Wake all waiting threads
22}
23
24// Consumer
25void consumer() {
26    while (true) {
27        unique_lock<mutex> lock(mtx);
28        cv.wait(lock, []{
29            return !dataQueue.empty() || done;
30        });
31
32        if (dataQueue.empty() && done) break;
33
34        int data = dataQueue.front();
35        dataQueue.pop();
36        lock.unlock();
37
38        cout << "Consumed: " << data << endl;
39    }
40}
41
42// wait_for with timeout
43cv.wait_for(lock, chrono::seconds(1), []{ return ready; });

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In