Leetcode—1115. 交替打印 FooBar【中等】(多线程)

2024每日刷题(180)

Leetcode---1115. 交替打印 FooBar

C++实现代码

cpp 复制代码
class FooBar {
private:
    int n;
    sem_t fooSem;
    sem_t barSem;

public:
    FooBar(int n) {
        this->n = n;
        sem_init(&fooSem, 0, 1);
        sem_init(&barSem, 0, 0);
    }

    ~FooBar() {
        sem_destroy(&fooSem);
        sem_destroy(&barSem);
    }

    void foo(function<void()> printFoo) {
        
        for (int i = 0; i < n; i++) {
            sem_wait(&fooSem);
        	// printFoo() outputs "foo". Do not change or remove this line.
        	printFoo();
            sem_post(&barSem);
        }
    }

    void bar(function<void()> printBar) {
        
        for (int i = 0; i < n; i++) {
            sem_wait(&barSem);
        	// printBar() outputs "bar". Do not change or remove this line.
        	printBar();
            sem_post(&fooSem);
        }
    }
};

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
2401_881244404 分钟前
牛客周赛99
c++
课堂剪切板2 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)33 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.4 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
十五年专注C++开发6 小时前
CMake基础:条件判断详解
c++·跨平台·cmake·自动化编译
森焱森6 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack8 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6738 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
whoarethenext8 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
写个博客9 小时前
暑假算法日记第一天
算法