You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查询Boost ASIO指定strand上等待的完成处理程序数量

如何统计Boost ASIO strand上等待的完成处理程序数量

Boost.ASIO 官方未提供公开的稳定API,可直接查询指定strand上的待执行完成处理程序数量。

应用层可靠实现方案

很多开发者担心自行维护计数器会因为定时器取消、套接字异常关闭出现计数不一致,本质是对ASIO执行模型存在误解:ASIO 保证所有提交的异步操作的完成处理程序,无论操作最终是成功、失败、被取消,最终都会被调度执行,因此只需用RAII机制封装计数逻辑,就能实现完全可靠的计数,不会出现计数漂移问题。

推荐的封装实现示例如下:

#include <boost/asio.hpp>
#include <atomic>
#include <memory>

template <typename Executor, typename Handler>
auto submit_to_strand(Executor strand, std::atomic<std::size_t>& pending_counter, Handler&& handler)
{
    // 提交任务前计数+1
    pending_counter.fetch_add(1, std::memory_order_relaxed);
    return boost::asio::post(strand, 
        [&pending_counter, h = std::forward<Handler>(handler)] () mutable {
            // RAII守卫:无论处理程序正常返回、抛出异常,都会触发计数-1
            auto decrement_guard = std::shared_ptr<void>(nullptr, 
                [&pending_counter](void*) {
                    pending_counter.fetch_sub(1, std::memory_order_relaxed);
                }
            );
            std::move(h)();
        }
    );
}

使用逻辑:

  • 为每个需要统计的strand,绑定一个独立的std::atomic<std::size_t>计数器
  • 所有向该strand提交的任务、异步操作完成处理程序,都通过上述submit_to_strand接口提交
  • 需要获取近似待处理任务数时,直接调用pending_counter.load(std::memory_order_relaxed)即可,返回值符合你要求的近似精度。

不推荐的实现方式

部分开发者尝试通过访问ASIO内部strand实现的私有成员获取队列长度,该方案严重依赖特定Boost版本的内部实现逻辑,无跨版本兼容性,生产环境不建议使用。


内容的提问来源于stack exchange,提问作者Kai Petzke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:24:04