Monday, February 17, 2020

1115. Print FooBar Alternately

Q:

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.

A:

class FooBar {
private:
    int n;
    mutex m1;
    mutex m2;
    
public:
    FooBar(int n) {
        this->n = n;
        m1.unlock();
        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();
        }
    }
};



1 comment:

  1. Water Hack Burns 2lb of Fat OVERNIGHT

    At least 160,000 men and women are trying a easy and SECRET "water hack" to drop 2lbs every night as they sleep.

    It's effective and it works all the time.

    Just follow these easy step:

    1) Go grab a drinking glass and fill it half the way

    2) Proceed to use this awesome HACK

    and become 2lbs thinner the next day!

    ReplyDelete