-
Notifications
You must be signed in to change notification settings - Fork 10
/
foobar.cpp
41 lines (33 loc) · 832 Bytes
/
foobar.cpp
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
class FooBar {
private:
int n;
std::mutex mtx;
std::condition_variable cv;
bool fooTurn = true; // is it foo's turn to run?
public:
FooBar(int n) {
this->n = n;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
std::unique_lock<std::mutex> lock(mtx);
while(fooTurn==false){
cv.wait(lock);
}
printFoo();
fooTurn = false;
cv.notify_one();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
std::unique_lock<std::mutex> lock(mtx);
while(fooTurn){
cv.wait(lock);
}
printBar();
fooTurn = true;
cv.notify_one();
}
}
};