第36天。
今天的题目是Print FooBar Alternately:
一道简单的并发的题目,交替输出Foo
和Bar
,就是要并发的两个线程,按顺序交替执行,我们可以用两个mutxe
去实现:
1class FooBar {2private:3 int n;4 mutex m1, m2;5public:6 FooBar(int n) {7 this->n = n;8 m2.lock();9 }10
11 void foo(function<void()> printFoo) {12
13 for (int i = 0; i < n; i++) {14 m1.lock();15 // printFoo() outputs "foo". Do not change or remove this line.15 collapsed lines
16 printFoo();17 m2.unlock();18 }19 }20
21 void bar(function<void()> printBar) {22
23 for (int i = 0; i < n; i++) {24 m2.lock();25 // printBar() outputs "bar". Do not change or remove this line.26 printBar();27 m1.unlock();28 }29 }30};