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);
        }
    }
};

运行结果

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

相关推荐
一个人旅程~20 小时前
虚数与量子迷踪
经验分享·笔记·微信·电脑·量子计算
郝学胜-神的一滴20 小时前
Leetcode 969 煎饼排序✨:翻转间的数组排序艺术
数据结构·c++·算法·leetcode·面试
炸膛坦客1 天前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
智者知已应修善业1 天前
【proteus中lm339电压滞回比较器达到三角波转换成方波】2023-4-13
驱动开发·经验分享·笔记·硬件架构·proteus·硬件工程
I_LPL1 天前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱1 天前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073211 天前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
炸膛坦客1 天前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_831824961 天前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~1 天前
【C++小游戏】2048
开发语言·c++