返回介绍

solution / 1100-1199 / 1114.Print in Order / README_EN

发布于 2024-06-17 01:03:23 字数 6890 浏览 0 评论 0 收藏 0

1114. Print in Order

中文文档

Description

Suppose we have a class:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

 

Example 1:

Input: nums = [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.

Example 2:

Input: nums = [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.

 

Constraints:

  • nums is a permutation of [1, 2, 3].

Solutions

Solution 1: Multithreading + Lock or Semaphore

We can use three semaphores $a$, $b$, and $c$ to control the execution order of the three threads. Initially, the count of semaphore $a$ is $1$, and the counts of $b$ and $c$ are $0$.

When thread $A$ executes the first() method, it first needs to acquire semaphore $a$. After acquiring successfully, it executes the first() method, and then releases semaphore $b$. This allows thread $B$ to acquire semaphore $b$ and execute the second() method.

When thread $B$ executes the second() method, it first needs to acquire semaphore $b$. After acquiring successfully, it executes the second() method, and then releases semaphore $c$. This allows thread $C$ to acquire semaphore $c$ and execute the third() method.

When thread $C$ executes the third() method, it first needs to acquire semaphore $c$. After acquiring successfully, it executes the third() method, and then releases semaphore $a$. This allows thread $A$ to acquire semaphore $a$ and execute the first() method.

The time complexity is $O(1)$, and the space complexity is $O(1)$.

class Foo:
  def __init__(self):
    self.l2 = threading.Lock()
    self.l3 = threading.Lock()
    self.l2.acquire()
    self.l3.acquire()

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

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

  def third(self, printThird: 'Callable[[], None]') -> None:
    self.l3.acquire()
    printThird()
class Foo {
  private Semaphore a = new Semaphore(1);
  private Semaphore b = new Semaphore(0);
  private Semaphore c = new Semaphore(0);

  public Foo() {
  }

  public void first(Runnable printFirst) throws InterruptedException {
    a.acquire(1);
    // printFirst.run() outputs "first". Do not change or remove this line.
    printFirst.run();
    b.release(1);
  }

  public void second(Runnable printSecond) throws InterruptedException {
    b.acquire(1);
    // printSecond.run() outputs "second". Do not change or remove this line.
    printSecond.run();
    c.release(1);
  }

  public void third(Runnable printThird) throws InterruptedException {
    c.acquire(1);
    // printThird.run() outputs "third". Do not change or remove this line.
    printThird.run();
    a.release(1);
  }
}
class Foo {
private:
  mutex m2, m3;

public:
  Foo() {
    m2.lock();
    m3.lock();
  }

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

  void second(function<void()> printSecond) {
    m2.lock();
    printSecond();
    m3.unlock();
  }

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

Solution 2

from threading import Semaphore


class Foo:
  def __init__(self):
    self.a = Semaphore(1)
    self.b = Semaphore(0)
    self.c = Semaphore(0)

  def first(self, printFirst: 'Callable[[], None]') -> None:
    self.a.acquire()
    # printFirst() outputs "first". Do not change or remove this line.
    printFirst()
    self.b.release()

  def second(self, printSecond: 'Callable[[], None]') -> None:
    self.b.acquire()
    # printSecond() outputs "second". Do not change or remove this line.
    printSecond()
    self.c.release()

  def third(self, printThird: 'Callable[[], None]') -> None:
    self.c.acquire()
    # printThird() outputs "third". Do not change or remove this line.
    printThird()
    self.a.release()
#include <semaphore.h>

class Foo {
private:
  sem_t a, b, c;

public:
  Foo() {
    sem_init(&a, 0, 1);
    sem_init(&b, 0, 0);
    sem_init(&c, 0, 0);
  }

  void first(function<void()> printFirst) {
    sem_wait(&a);
    // printFirst() outputs "first". Do not change or remove this line.
    printFirst();
    sem_post(&b);
  }

  void second(function<void()> printSecond) {
    sem_wait(&b);
    // printSecond() outputs "second". Do not change or remove this line.
    printSecond();
    sem_post(&c);
  }

  void third(function<void()> printThird) {
    sem_wait(&c);
    // printThird() outputs "third". Do not change or remove this line.
    printThird();
    sem_post(&a);
  }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文