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() {
    mutex2.lock();
    mutex3.lock();
  }

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

  void second(function<void()> printSecond) {
    mutex2.lock();
    printSecond();
    mutex3.unlock();
  }

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

 private:
  mutex mutex2;
  mutex mutex3;
};
 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.mutex2 = Lock()
    self.mutex3 = Lock()
    self.mutex2.acquire()
    self.mutex3.acquire()

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

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

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