NexusForce 1.0.0
A rigorously engineered full-stack C++ backend library.
载入中...
搜索中...
未找到
channel.hpp
浏览该文件的文档.
1#ifndef NEFORCE_CORE_ASYNC_CHANNEL_HPP__
2#define NEFORCE_CORE_ASYNC_CHANNEL_HPP__
3
11
15NEFORCE_BEGIN_NAMESPACE__
16
22
33template <typename T>
34class channel {
35private:
36 size_t capacity_;
37 bool closed_{false};
38 mutable mutex mutex_;
40 deque<T> buffer_;
41
42public:
48 explicit channel(size_t capacity = capacity_max) :
49 capacity_(capacity) {}
50
51 channel(const channel&) = delete;
52 channel& operator=(const channel&) = delete;
53
57 static constexpr size_t capacity_max = numeric_traits<size_t>::max();
58
64 bool try_write(T value) {
66 if (closed_) {
67 return false;
68 }
69 if (capacity_ > 0 && buffer_.size() >= capacity_) {
70 return false;
71 }
72 buffer_.push_back(move(value));
73 cv_.notify_one();
74 return true;
75 }
76
82 bool write(T value) {
84 cv_.wait(lock, [this] {
85 return closed_ || (capacity_ == 0 && buffer_.empty()) || (capacity_ > 0 && buffer_.size() < capacity_);
86 });
87 if (closed_) {
88 return false;
89 }
90 buffer_.push_back(move(value));
91 cv_.notify_one();
92 return true;
93 }
94
100 bool try_read(T& out) {
101 unique_lock<mutex> lock{mutex_};
102 if (buffer_.empty()) {
103 return false;
104 }
105 out = move(buffer_.front());
106 buffer_.pop_front();
107 cv_.notify_one();
108 return true;
109 }
110
116 bool read(T& out) {
117 unique_lock<mutex> lock{mutex_};
118 cv_.wait(lock, [this] { return closed_ || !buffer_.empty(); });
119 if (buffer_.empty()) {
120 return false;
121 }
122 out = move(buffer_.front());
123 buffer_.pop_front();
124 cv_.notify_one();
125 return true;
126 }
127
134 void close() {
135 lock<mutex> lock{mutex_};
136 closed_ = true;
137 cv_.notify_all();
138 }
139
144 NEFORCE_NODISCARD bool is_closed() const noexcept {
145 lock<mutex> lock{mutex_};
146 return closed_;
147 }
148
153 NEFORCE_NODISCARD size_t size() const noexcept {
154 lock<mutex> lock{mutex_};
155 return buffer_.size();
156 }
157
162 NEFORCE_NODISCARD bool empty() const noexcept {
163 lock<mutex> lock{mutex_};
164 return buffer_.empty();
165 }
166};
167 // Channel
169
170NEFORCE_END_NAMESPACE__
171#endif // NEFORCE_CORE_ASYNC_CHANNEL_HPP__
有限容量的 CSP 消息通道
bool read(T &out)
读取消息(阻塞直到有数据或通道关闭)
bool is_closed() const noexcept
检查通道是否已关闭
channel(size_t capacity=capacity_max)
构造函数
bool try_read(T &out)
尝试读取消息(非阻塞)
bool try_write(T value)
尝试发送消息(非阻塞)
bool empty() const noexcept
检查缓冲区是否为空
bool write(T value)
发送消息(阻塞直到空间可用或通道关闭)
void close()
关闭通道
static constexpr size_t capacity_max
最大容量常量
size_t size() const noexcept
当前缓冲消息数量
双端队列容器
锁管理器模板
非递归互斥锁
static constexpr T max() noexcept
获取类型的最大值
独占锁管理器模板
条件变量行为
双端队列容器
constexpr Iterator2 move(Iterator1 first, Iterator1 last, Iterator2 result) noexcept(noexcept(inner::__move_aux(first, last, result)))
移动范围元素
互斥锁