Skip to content

1114. Print in Order 👍

  • Time:
  • Space:
 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
class Foo {
 public:
  Foo() {
    firstDone.lock();
    secondDone.lock();
  }

  void first(function<void()> printFirst) {
    printFirst();
    firstDone.unlock();
  }

  void second(function<void()> printSecond) {
    firstDone.lock();
    printSecond();
    secondDone.unlock();
  }

  void third(function<void()> printThird) {
    secondDone.lock();
    printThird();
  }

 private:
  mutex firstDone;
  mutex secondDone;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Foo {
  public void first(Runnable printFirst) throws InterruptedException {
    printFirst.run();
    firstDone.incrementAndGet();
  }

  public void second(Runnable printSecond) throws InterruptedException {
    while (firstDone.get() != 1)
      ;
    printSecond.run();
    secondDone.incrementAndGet();
  }

  public void third(Runnable printThird) throws InterruptedException {
    while (secondDone.get() != 1)
      ;
    printThird.run();
  }

  private AtomicInteger firstDone = new AtomicInteger();
  private AtomicInteger secondDone = new AtomicInteger();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from threading import Lock


class Foo:
  def __init__(self):
    self.firstDone = Lock()
    self.secondDone = Lock()
    self.firstDone.acquire()
    self.secondDone.acquire()

  def first(self, printFirst: 'Callable[[], None]') -> None:
    printFirst()
    self.firstDone.release()

  def second(self, printSecond: 'Callable[[], None]') -> None:
    self.firstDone.acquire()
    printSecond()
    self.secondDone.release()

  def third(self, printThird: 'Callable[[], None]') -> None:
    self.secondDone.acquire()
    printThird()