forked from keineahnung2345/leetcode-cpp-practices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1115. Print FooBar Alternately.cpp
39 lines (34 loc) · 1.04 KB
/
1115. Print FooBar Alternately.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
//Runtime: 336 ms, faster than 62.59% of C++ online submissions for Print FooBar Alternately.
//Memory Usage: 10.5 MB, less than 100.00% of C++ online submissions for Print FooBar Alternately.
class FooBar {
private:
int n;
mutex mtx;
condition_variable cv;
bool isFoo;
public:
FooBar(int n) {
this->n = n;
this->isFoo = true;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
unique_lock<mutex> lck(mtx);
cv.wait(lck, [this](){return isFoo;});
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
isFoo = false;
cv.notify_all();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
unique_lock<mutex> lck(mtx);
cv.wait(lck, [this](){return !isFoo;});
// printBar() outputs "bar". Do not change or remove this line.
printBar();
isFoo = true;
cv.notify_all();
}
}
};