[Programming Problem] Print FooBar Alternately

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.

[Problem Link]

Why use Semaphore and not ReentrantLock?

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the “lock” can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

class FooBar {
    private int n;
    private final Semaphore mutexFoo = new Semaphore(1);
    private final Semaphore mutexBar = new Semaphore(1);
 
    public FooBar(int n) {
        this.n = n;
        try {
            mutexBar.acquire();
        } catch ( Exception e ) {}
    }
 
    public void foo(Runnable printFoo) throws InterruptedException {
 
        for (int i = 0; i < n; i++) {
 
            // printFoo.run() outputs "foo". Do not change or remove this line.
            mutexFoo.acquire();
            printFoo.run();
            mutexBar.release();
        }
    }
 
    public void bar(Runnable printBar) throws InterruptedException {
 
        for (int i = 0; i < n; i++) {     
            // printBar.run() outputs "bar". Do not change or remove this line.
            mutexBar.acquire();
            printBar.run();
            mutexFoo.release();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *