欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Leetcode-1115. 交替打印 FooBar [medium] (多线程)

最编程 2024-10-17 12:15:47
...
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); } } };