C++多线程学习07

Actor和CSP设计模式

参考:恋恋风辰官方博客

#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>

/*
    CSP设计模式
*/


template<typename T>
class Channel
{
private:
    std::queue<T>              queue_;
    std::mutex                 mtx_;
    std::condition_variable    cv_producer_;
    std::condition_variable    cv_comsumer_;
    size_t                     capacity_;
    bool                       closed_;

public:
    Channel(size_t capacity = 0): capacity_(capacity), closed_(false){}

    bool send(T value)
    {
        std::unique_lock<std::mutex> lock(mtx_);
        cv_producer_.wait(lock, [this]() {
            // 对于无缓存channel, 应该等待所有消费者准备好
            return (capacity_ == 0 && queue_.empty()) || queue_.size() < capacity_ || closed_;
            });

        if (closed_)
            return false;

        queue_.push(value);
        cv_comsumer_.notify_one();
        return true;
    }

    bool receive(T& value)
    {
        std::unique_lock<std::mutex>   lock(mtx_);
        cv_comsumer_.wait(lock, [this]() {
            return !queue_.empty() || closed_;
            });

        if (closed_ && queue_.front())
            return false;

        value = queue_.front();
        queue_.pop();
        cv_producer_.notify_one();
        return true;
    }

    void close()
    {
        std::unique_lock<std::mutex>    lock(mtx_);
        closed_ = true;
        cv_producer_.notify_all();
        cv_comsumer_.notify_all();
    }
};

int main()
{
    Channel<int>    ch(10);     // 无缓存通道
    std::thread producer([&]() {
        for (int i = 0; i < 5; i++) {
            ch.send(i);
            std::cout << "Send: " << i << std::endl;
        }
        ch.close();
        });

    std::thread consumer([&]() {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));        // 消费者故意延迟
        int val;
        while (ch.receive(val))
        {
            std::cout << "Received: " << val << std::endl;
        }
        });

    producer.join();
    consumer.join();

    std::cout << "Finished! \n";
    return 0;
}

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值