首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode 1114 - Print in Order

LeetCode 1114 - Print in Order

作者头像
Reck Zhang
发布于 2021-08-11 11:13:25
发布于 2021-08-11 11:13:25
9150
举报
文章被收录于专栏:Reck ZhangReck Zhang

Print in Order

Desicription

Suppose we have a class:

代码语言:javascript
复制
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().

Example 1:

代码语言:javascript
复制
Input: [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:

代码语言:javascript
复制
Input: [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.

Note:

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

Solution

代码语言:javascript
复制
class Foo {
private:
    std::promise<void> p1;
    std::promise<void> p2;

public:
    void first(const std::function<void()>& printFirst) {
        printFirst();
        p1.set_value();
    }

    void second(const std::function<void()>& printSecond) {
        p1.get_future().wait();
        printSecond();
        p2.set_value();
    }

    void third(const std::function<void()>& printThird) {
        p2.get_future().wait();
        printThird();
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-11-29,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • Print in Order
    • Desicription
    • Example 1:
    • Example 2:
    • Note:
    • Solution
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档