NexusForce 1.0.0
A rigorously engineered full-stack C++ backend library.
载入中...
搜索中...
未找到
strand.hpp
浏览该文件的文档.
1#ifndef NEFORCE_CORE_ASYNC_STRAND_HPP__
2#define NEFORCE_CORE_ASYNC_STRAND_HPP__
3
10
16NEFORCE_BEGIN_NAMESPACE__
17
23
30class strand {
31public:
33 using handler_type = function<void()>;
34
35private:
36 struct impl {
37 io_context* ctx;
38 atomic<bool> locked_{false};
39 lock_free_queue<function<void()>> queue_;
40
41 explicit impl(io_context& c) :
42 ctx(&c) {}
43
44 void drain_one(const shared_ptr<impl>& self) {
45 bool expected = false;
46 if (!self->locked_.compare_exchange_strong(expected, true, memory_order_acquire, memory_order_relaxed)) {
47 return;
48 }
49 auto handler = self->queue_.try_pop();
50 if (handler) {
51 auto shared_handler = make_shared<function<void()>>(move(*handler));
52 self->ctx->post([self, shared_handler]() {
53 (*shared_handler)();
54 self->locked_.store(false, memory_order_release);
55 self->drain_one(self);
56 });
57 } else {
58 self->locked_.store(false, memory_order_release);
59 }
60 }
61 };
62
63 shared_ptr<impl> impl_;
64
65public:
72 explicit strand(io_context& ctx) :
73 impl_(make_shared<impl>(ctx)) {}
74
81 void post(handler_type handler) {
82 impl_->queue_.push(move(handler));
83 impl_->drain_one(impl_);
84 }
85
93 void dispatch(handler_type handler) {
94 bool expected = false;
95 if (impl_->locked_.compare_exchange_strong(expected, true, memory_order_acquire, memory_order_relaxed)) {
96 handler();
97 impl_->locked_.store(false, memory_order_release);
98 impl_->drain_one(impl_);
99 } else {
100 post(move(handler));
101 }
102 }
103
108 NEFORCE_NODISCARD io_context::executor get_executor() const noexcept { return impl_->ctx->get_executor(); }
109
114 NEFORCE_NODISCARD io_context& context() const noexcept { return *impl_->ctx; }
115};
116 // Strand
118
119NEFORCE_END_NAMESPACE__
120#endif // NEFORCE_CORE_ASYNC_STRAND_HPP__
原子类型完整实现
函数包装器主模板声明
io_context 的执行器句柄
统一异步操作核心
共享智能指针类模板
void post(handler_type handler)
投递 handler 到 strand 队列末尾
io_context::executor get_executor() const noexcept
获取关联的 io_context 执行器
void dispatch(handler_type handler)
尽可能在当前线程同步执行 handler
function< void()> handler_type
handler 类型
io_context & context() const noexcept
获取关联的 io_context 引用
strand(io_context &ctx)
构造 strand
通用函数包装器
constexpr auto memory_order_release
释放内存顺序常量
constexpr auto memory_order_acquire
获取内存顺序常量
constexpr auto memory_order_relaxed
宽松内存顺序常量
enable_if_t<!is_unbounded_array_v< T > &&is_constructible_v< T, Args... >, shared_ptr< T > > make_shared(Args &&... args)
融合分配创建共享指针
constexpr Iterator2 move(Iterator1 first, Iterator1 last, Iterator2 result) noexcept(noexcept(inner::__move_aux(first, last, result)))
移动范围元素
统一异步操作核心
共享智能指针实现
通用原子类型模板