Skip to content

1115. Print FooBar Alternately 👍

 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
32
33
34
35
36
37
// LeetCode doesn't support C++20 yet, so we don't have std::counting_semaphore
// or binary_semaphore.
#include <semaphore.h>

class FooBar {
 public:
  FooBar(int n) : n(n) {
    sem_init(&fooSemaphore, /*pshared=*/0, /*value=*/1);
    sem_init(&barSemaphore, /*pshared=*/0, /*value=*/0);
  }

  ~FooBar() {
    sem_destroy(&fooSemaphore);
    sem_destroy(&barSemaphore);
  }

  void foo(function<void()> printFoo) {
    for (int i = 0; i < n; ++i) {
      sem_wait(&fooSemaphore);
      printFoo();
      sem_post(&barSemaphore);
    }
  }

  void bar(function<void()> printBar) {
    for (int i = 0; i < n; ++i) {
      sem_wait(&barSemaphore);
      printBar();
      sem_post(&fooSemaphore);
    }
  }

 private:
  const int n;
  sem_t fooSemaphore;
  sem_t barSemaphore;
};
 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
class FooBar {
  public FooBar(int n) {
    this.n = n;
  }

  public void foo(Runnable printFoo) throws InterruptedException {
    for (int i = 0; i < n; ++i) {
      fooSemaphore.acquire();
      printFoo.run();
      barSemaphore.release();
    }
  }

  public void bar(Runnable printBar) throws InterruptedException {
    for (int i = 0; i < n; ++i) {
      barSemaphore.acquire();
      printBar.run();
      fooSemaphore.release();
    }
  }

  private int n;
  private Semaphore fooSemaphore = new Semaphore(1);
  private Semaphore barSemaphore = new Semaphore(0);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from threading import Semaphore


class FooBar:
  def __init__(self, n):
    self.n = n
    self.fooSemaphore = Semaphore(1)
    self.barSemaphore = Semaphore(0)

  def foo(self, printFoo: 'Callable[[], None]') -> None:
    for _ in range(self.n):
      self.fooSemaphore.acquire()
      printFoo()
      self.barSemaphore.release()

  def bar(self, printBar: 'Callable[[], None]') -> None:
    for _ in range(self.n):
      self.barSemaphore.acquire()
      printBar()
      self.fooSemaphore.release()