交替打印FooBar

题目: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();
        }
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值