leetcode---1114.按序打印

leetcode---1114.按序打印,第1张

leetcode---1114.按序打印


第一次做多线程的题目,以前学过的 *** 作系统好多知识都忘记了,题解描述的很详细,可以用锁或者信号量来实现。
不同编程语言实现的方法不同,python用到的是threading库,c++中用到的是semaphore.h这个库

#include

class Foo {
protected:
    sem_t firstJobDone;
    sem_t secondJobDone;
    
public:
    Foo() {
        sem_init(&firstJobDone, 0, 0);
        sem_init(&secondJobDone, 0, 0);
    }

    void first(function printFirst) {
        
        // printFirst() outputs "first". Do not change or remove this line.
        printFirst();
        sem_post(&firstJobDone);
    }

    void second(function printSecond) {
        sem_wait(&firstJobDone);
        // printSecond() outputs "second". Do not change or remove this line.
        printSecond();
        sem_post(&secondJobDone);
    }

    void third(function printThird) {
        sem_wait(&secondJobDone);
        // printThird() outputs "third". Do not change or remove this line.
        printThird();
    }
};

其中,sem_init(&firstJobDone, 0, 0);这句话中,后面两个0的含义为:

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5700372.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存