LeetCode 1114. 按序打印

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我们提供了一个类:

public class Foo {
  public void one() { print("one"); }
  public void two() { print("two"); }
  public void three() { print("three"); }
}

三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。

示例1:

输入: [1,2,3]
输出: “onetwothree”
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 “onetwothree”。

示例2:

输入: [1,3,2]
输出: “onetwothree”
解释:
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 “onetwothree”。

题解:

为了让线程之间能够进行同步,我们可以给线程上一个mutex锁。

首先我们要建立两个锁:

mutex mt2;
mutex mt3;

这两个锁也就对应了输出 two 还有输出 three 的两个function。
如果我们在初始化的时候将其锁住,并且在first() 里面打开mt2,在second里面打开mt3。就能够保证无论以任何顺序使用这三个方法,都能以onetwothree的顺序输出。

class Foo {
public:
    mutex mt2; //lock for void second(function printSecond)
    mutex mt3; //lock for third()
    Foo() {
        mt2.lock();
        mt3.lock();
    }

    void first(function printFirst) {
        //there's no lock in this function
        // printFirst() outputs "first". Do not change or remove this line.
        printFirst();
        mt2.unlock();
    }

    void second(function printSecond) {
        mt2.lock(); //lock
        // printSecond() outputs "second". Do not change or remove this line.
        printSecond();
        mt2.unlock();
        mt3.unlock();
    }

    void third(function printThird) {
        mt3.lock(); //lock
        // printThird() outputs "third". Do not change or remove this line.
        printThird();
        mt3.unlock();
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据