Print FooBar Alternately

Dec 12, 2019

第36天。

今天的题目是Print FooBar Alternately:

一道简单的并发的题目,交替输出FooBar,就是要并发的两个线程,按顺序交替执行,我们可以用两个mutxe去实现:

class FooBar {
private:
    int n;
    mutex m1, 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();
        }
    }
};
LeetCodeLeetCode

Redundant Connection

Binary Tree Pruning

comments powered by Disqus