-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcondition_var.cpp
More file actions
42 lines (35 loc) · 792 Bytes
/
condition_var.cpp
File metadata and controls
42 lines (35 loc) · 792 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <string>
#include <chrono>
using namespace std;
std::mutex mt;
std::condition_variable cv;
int counter;
bool should_continue() {
return counter<10;
}
void helper () {
while(should_continue()) {
std::unique_lock<std::mutex> lk(mt);
cv.wait(lk, []{ return ((counter%2)==1); });
cout << __func__ << " has count: " << counter++ << std::endl;
cv.notify_all();
}
}
int main() {
std::thread worker(helper);
while (should_continue()) {
{
std::lock_guard<std::mutex> lock(mt);
cout << __func__ << " has count: " << counter++ << std::endl;
}
cv.notify_all();
std::unique_lock<std::mutex> lock(mt);
cv.wait(lock, []{return counter%2==0; });
}
worker.join();
return 0;
}