2024每日刷题(182)
Leetcode—1117. H2O 生成
C++实现代码
class H2O {
public:
H2O() {
sem_init(&hydrogenSem, 0, 1);
sem_init(&oxygenSem, 0, 0);
}
~H2O() {
sem_destroy(&hydrogenSem);
sem_destroy(&oxygenSem);
}
void hydrogen(function<void()> releaseHydrogen) {
sem_wait(&hydrogenSem);
++n;
// releaseHydrogen() outputs "H". Do not change or remove this line.
releaseHydrogen();
if(n % 2 == 0) {
sem_post(&oxygenSem);
} else {
sem_post(&hydrogenSem);
}
}
void oxygen(function<void()> releaseOxygen) {
sem_wait(&oxygenSem);
// releaseOxygen() outputs "O". Do not change or remove this line.
releaseOxygen();
sem_post(&hydrogenSem);
}
private:
int n = 0;
sem_t hydrogenSem;
sem_t oxygenSem;
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!