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

Boost ASIO:默认完成令牌关联执行器是什么?本地绑定能否提性能?

Boost.Asio协程执行器相关问题解答

参考示例代码

#include <boost/asio.hpp>
#include <print>
#include <thread>

namespace asio = boost::asio;

inline void out(auto const& msg) {
  static const std::hash<std::thread::id> h {};
  std::println("T{} {}", h(std::this_thread::get_id()) % 100, msg);
}

asio::awaitable<void> f(auto strand) {
  auto executor = co_await asio::this_coro::executor;

  auto to_strd = bind_executor(strand, asio::deferred);
  auto to_coro = bind_executor(executor, asio::deferred);

  out("I'm on main");
  co_await dispatch(strand, asio::deferred);
  out("Still on main, asio::deferred has an associated executor");
  co_await dispatch(to_strd);
  out("Now I'm on the strand");
  co_await dispatch(asio::deferred);
  out("Back on main, using asio::deferred's associated executor");
  co_await dispatch(to_strd);
  out("Strand again");
  co_await dispatch(to_coro);
  out("Was this faster than dispatch(asio::deferred)?");
}

int main() {
  asio::io_context io;
  asio::thread_pool tp(1);

  co_spawn(io, f(make_strand(tp)), asio::detached);

  out("<--- this is main");
  io.run();
  tp.join();
}

问题背景

当使用dispatch()或post()调用Asio提供的deferred、use_awaitable等完成令牌时,传入的执行器会被忽略,转而使用this_coro::executor(本人推测)。

问题解答

1. dispatch()最终使用this_coro::executor的机制是什么?

Asio的协程完成令牌(如deferred、use_awaitable)依赖**关联执行器(associated executor)**机制工作:

  • 当你在协程中调用dispatch(strand, asio::deferred)时,deferred本身是空类型,但Asio的异步操作启动逻辑会通过asio::get_associated_executor函数获取与令牌关联的执行器。
  • 对于协程上下文内的完成令牌,get_associated_executor会优先返回协程的默认执行器——也就是co_await asio::this_coro::executor拿到的对象。这个执行器是在co_spawn启动协程时就绑定到协程状态中的,存储在协程栈的内部结构里。
  • 因此dispatch()最终会使用协程关联的执行器调度后续操作,传入的strand会被忽略,除非你用bind_executor(strand, asio::deferred)显式将执行器与令牌绑定,此时get_associated_executor会返回绑定的strand。

2. 多次操作时,提前调用bind_executor()能否提升性能?

提前绑定执行器与deferred令牌,确实能减少每次dispatch()调用时的执行器解析开销,但收益场景有限:

  • 高频调用场景(比如循环中反复执行):每次调用dispatch(asio::deferred)都需要从协程状态中查找默认执行器,提前绑定可以避免重复的间接访问,降低微小延迟。
  • 低频调用场景:Asio的关联执行器查找逻辑本身非常轻量化,性能提升可以忽略不计。
  • 额外收益:提前绑定能让代码意图更清晰,明确指定后续操作的执行器,避免依赖隐式的协程默认执行器,提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:06:25