forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
print-foobar-alternately.cpp
70 lines (63 loc) · 1.58 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Time: O(n)
// Space: O(1)
class FooBar {
public:
FooBar(int n) : n_(n) {
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n_; ++i) {
{
unique_lock<mutex> l(m_);
cv_.wait(l, [this]() { return !curr_; });
curr_ = !curr_;
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
}
cv_.notify_one();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n_; ++i) {
{
unique_lock<mutex> l(m_);
cv_.wait(l, [this]() { return curr_; });
curr_ = !curr_;
// printBar() outputs "bar". Do not change or remove this line.
printBar();
}
cv_.notify_one();
}
}
private:
int n_;
bool curr_ = false;
mutex m_;
condition_variable cv_;
};
// Time: O(n)
// Space: O(1)
class FooBar2 {
public:
FooBar2(int n) : n_(n) {
m2_.lock();
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n_; ++i) {
m1_.lock();
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
m2_.unlock();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n_; ++i) {
m2_.lock();
// printBar() outputs "bar". Do not change or remove this line.
printBar();
m1_.unlock();
}
}
private:
int n_;
mutex m1_, m2_;
};