#pragma once #include #include #include #include namespace Void::Concurrency { // Bounded multi-producer multi-consumer channel. // send/receive block until space/item is available or the channel is // closed. template class Channel { public: explicit Channel(std::size_t capacity) : cap_{capacity} {} Channel(const Channel&) = delete; Channel& operator=(const Channel&) = delete; // Block until space is available. Returns false if the channel is // closed. bool send(T value) { std::unique_lock lock{mu_}; not_full_.wait( lock, [this] { return buf_.size() < cap_ || closed_; }); if (closed_) { return false; } buf_.push(std::move(value)); not_empty_.notify_one(); return true; } // Block until an item is available. Returns nullopt if closed and // empty. std::optional receive() { std::unique_lock lock{mu_}; not_empty_.wait(lock, [this] { return !buf_.empty() || closed_; }); if (buf_.empty()) { return std::nullopt; } auto val = std::move(buf_.front()); buf_.pop(); not_full_.notify_one(); return val; } // Non-blocking send. Returns false if full or closed. bool try_send(T value) { std::unique_lock lock{mu_}; if (closed_ || buf_.size() >= cap_) { return false; } buf_.push(std::move(value)); not_empty_.notify_one(); return true; } // Non-blocking receive. Returns nullopt if empty. std::optional try_receive() { std::unique_lock lock{mu_}; if (buf_.empty()) { return std::nullopt; } auto val = std::move(buf_.front()); buf_.pop(); not_full_.notify_one(); return val; } void close() { { std::unique_lock lock{mu_}; closed_ = true; } not_full_.notify_all(); not_empty_.notify_all(); } bool is_closed() const { std::unique_lock lock{mu_}; return closed_; } std::size_t size() const { std::unique_lock lock{mu_}; return buf_.size(); } bool empty() const { std::unique_lock lock{mu_}; return buf_.empty(); } std::size_t capacity() const noexcept { return cap_; } private: std::size_t cap_; std::queue buf_; mutable std::mutex mu_; std::condition_variable not_full_; std::condition_variable not_empty_; bool closed_{false}; }; } // namespace Void::Concurrency