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

运行结果

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

相关推荐
Yzzz-F几秒前
P4145 上帝造题的七分钟 2 / 花神游历各国[线段树 区间开方(剪枝) + 区间求和]
算法·机器学习·剪枝
CSDN_RTKLIB1 分钟前
CMake成果打包
c++
Zzz不能停3 分钟前
堆排序算法及大小堆区别
数据结构·算法
来鼓AI6 分钟前
私域流量时代客服变革:3大转型路径重构增长引擎
经验分享
Yu_Lijing11 分钟前
基于C++的《Head First设计模式》笔记——工厂模式
c++·笔记·设计模式
zd84510150013 分钟前
stm32f407 电机多轴联动算法
stm32·单片机·算法
十五年专注C++开发13 分钟前
CMake进阶:核心命令get_filename_component 完全详解
开发语言·c++·cmake·跨平台编译
代码游侠15 分钟前
应用——Linux FrameBuffer图形显示与多线程消息系统项目
linux·运维·服务器·开发语言·前端·算法
Eloudy15 分钟前
矩阵张量积(Kronecker积)的代数性质与定理
算法·量子计算
gravity_w20 分钟前
vscode配置SSH远程服务器
服务器·经验分享·vscode·ssh