-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathPrint FooBar Alternately.cpp
72 lines (54 loc) · 1.52 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
71
72
/*
Solution by Rahul Surana
***********************************************************
Suppose you are given the following code:
class FooBar {
public void foo() {
for (int i = 0; i < n; i++) {
print("foo");
}
}
public void bar() {
for (int i = 0; i < n; i++) {
print("bar");
}
}
}
The same instance of FooBar will be passed to two different threads:
thread A will call foo(), while
thread B will call bar().
Modify the given program to output "foobar" n times.
***********************************************************
*/
#include <bits/stdc++.h>
class FooBar {
private:
int n;
std::mutex mtx;
std::condition_variable cv;
bool x = false;
public:
FooBar(int n) {
this->n = n;
}
void foo(function<void()> printFoo) {
std::unique_lock<std::mutex> lock(mtx);
for (int i = 0; i < n; i++) {
cv.wait(lock, [&] { return !x; });
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
x=true;
cv.notify_one();
}
}
void bar(function<void()> printBar) {
std::unique_lock<std::mutex> lock(mtx);
for (int i = 0; i < n; i++) {
cv.wait(lock, [&] { return x; });
// printBar() outputs "bar". Do not change or remove this line.
printBar();
x=false;
cv.notify_one();
}
}
};