2024每日刷题(180)
Leetcode—1115. 交替打印 FooBar
C++实现代码
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);}}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!