leetcode—1114.按序打印

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

#include<semaphore.h>

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

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

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

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

其中,sem_init(&firstJobDone, 0, 0);这句话中,后面两个0的含义为:
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>