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;
}