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.
Example 1:
Input: n = 1 Output: "foobar" Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.
Example 2:
Input: n = 2 Output: "foobarfoobar" Explanation: "foobar" is being output 2 times.
Solution: Mutex
C++
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 |
class FooBar { private: int n; std::mutex m1_; std::mutex m2_; public: FooBar(int n) { this->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(); } } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment