题目:https://leetcode-cn.com/problems/print-foobar-alternately/submissions/
打印保持顺序,与按序打印类似。
1.用两个信号量解决。
由于c++中没有原生信号量,所以用mutex和条件变量实现一个。
class Semaphore
{
public:
Semaphore(int value = 1) :count(value) {}
void Acquire()
{
unique_lock<mutex> lck(mtk);
if (--count < 0)//资源不足挂起线程
cv.wait(lck);
}
void Release()
{
unique_lock<mutex> lck(mtk);
if (++count <= 0)//有线程挂起,唤醒一个
cv.notify_one();
}
private:
int count;
mutex mtk;
condition_variable cv;
};
class FooBar {
private:
int n;
Semaphore sem1;
Semaphore sem2;
public:
FooBar(int n):sem1(1),sem2(0) {
this->n = n;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; ++i) {
sem1.Acquire();
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
sem2.Release();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; ++i) {
sem2.Acquire();
// printBar() outputs "bar". Do not change or remove this line.
printBar();
sem1.Release();
}
}
};
2.用两个互斥锁解决。
二进制信号量的作用与互斥锁功能相似,所以可以直接用mutex代替信号量实现。
class FooBar {
private:
int n;
std::mutex foo_mux;
std::mutex bar_mux;
public:
FooBar(int n) {
this->n = n;
bar_mux.lock();
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; ++i) {
foo_mux.lock();
// printFoo() outputs "foo". Do not change or remove this line.
printFoo();
bar_mux.unlock();
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; ++i) {
bar_mux.lock();
// printBar() outputs "bar". Do not change or remove this line.
printBar();
foo_mux.unlock();
}
}
};