Skip to content

Latest commit

 

History

History
98 lines (74 loc) · 3.06 KB

File metadata and controls

98 lines (74 loc) · 3.06 KB

1115. Print FooBar Alternately (Medium)

Date and Time: Feb 19, 2025, 23:56 (EST)

Link: https://leetcode.com/problems/print-foobar-alternately


Question:

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.


Constraints:

  • 1 <= n <= 1000

Walk-through:

Initialize two semaphores to control concurrency with sem_foo a higher priority, so we can always start with foo first. Everytime, we need to wait for sem_foo to be released, then we can release sem_boo. Do the same thing for boo().


C++ Solution:

class FooBar {
private:
    int n;
    sem_t sem_foo;
    sem_t sem_bar;

public:
    FooBar(int n) {
        this->n = n;
        sem_init(&sem_foo, 0, 1);   // Set foo with higher priority
        sem_init(&sem_bar, 0, 0);
    }

    void foo(function<void()> printFoo) {
        
        for (int i = 0; i < n; i++) {
            sem_wait(&sem_foo);
        	// printFoo() outputs "foo". Do not change or remove this line.
        	printFoo();
            sem_post(&sem_bar);
        }
    }

    void bar(function<void()> printBar) {
        
        for (int i = 0; i < n; i++) {
            sem_wait(&sem_bar);
        	// printBar() outputs "bar". Do not change or remove this line.
        	printBar();
            sem_post(&sem_foo);
        }
    }
};

CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms