1114.按序打印

链接:1114. 按序打印 - 力扣(LeetCode)

题解:

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>

class Func {
public:
    Func() : _turn(1) {   // 初始由 func1 打印
        // 创建三个线程,分别绑定成员函数
        _threads.push_back(std::thread(&Func::func1, this));
        _threads.push_back(std::thread(&Func::func2, this));
        _threads.push_back(std::thread(&Func::func3, this));
    }

    ~Func() {
        for (auto& t : _threads) {
            if (t.joinable()) t.join();
        }
    }

private:
    void func1() {
        for (int i = 0; i < 5; ++i) {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond1.wait(lock, [this]() { return _turn == 1; });
            std::cout << 1;
            _turn = 2;
            _cond2.notify_one();
        }
    }

    void func2() {
        for (int i = 0; i < 5; ++i) {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond2.wait(lock, [this]() { return _turn == 2; });
            std::cout << 2;
            _turn = 3;
            _cond3.notify_one();
        }
    }

    void func3() {
        for (int i = 0; i < 5; ++i) {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond3.wait(lock, [this]() { return _turn == 3; });
            std::cout << 3;
            _turn = 1;
            _cond1.notify_one();
        }
    }

    std::mutex _mutex;
    std::condition_variable _cond1, _cond2, _cond3;
    std::vector<std::thread> _threads;
    int _turn;  // 1→func1, 2→func2, 3→func3
};

int main() {
    Func f;
    // 析构时自动 join,等待所有线程完成
    std::cout << std::endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值