std::boost::asio::post / dispatch 使用哪个io_context?

Which io_context does std::boost::asio::post / dispatch use?

在使用 boost::asio 1.66 时,我在文档中读到 boost::asio::io_context::post 已弃用 boost::asio::postboost::asio::io_context::dispatch 也是如此。因为在它们之前 io_context 的成员函数之前,当然处理程序需要在某些 io_context 的上下文中执行,即 executor 我的问题是:

boost::asio::io_context::post 最简单的重载如何知道要使用哪个 io_contextexecutor

template< typename CompletionToken> DEDUCED post(CompletionToken && token); 的文档指出

Obtains the handler's associated executor object ex by performing get_associated_executor(handler).

但是 get_associated_executor 的文档对我来说也没有说清楚。我的猜测是由于 Template argument deduction 它可以在当前执行的处理程序中以某种方式获取它,但我想确定而且,如果我调用 post 在 boost::asio 处理程序之外。

文档的核心位于 associated_executor trait:

  • get()

    If T has a nested type executor_type, returns t.get_executor(). Otherwise returns ex.

  • executor_type

    If T has a nested type executor_type, T::executor_type. Otherwise Executor.

如果您的处理程序类型¹ 具有嵌套的 executor_type 类型,则假定调用 token.get() 将 return 使用正确的执行程序。

如果您将普通可调用对象传递给 post 而未指定 executor/execution 上下文,您将获得执行上下文的默认构造实例:boost::asio::system_executor.

这样做的目的是使用自定义处理程序类型实现 DoTheRightThing。例如。如果你 post 某个链上的东西,处理程序将被包装在特定于链实现的类型中。 associated_executor 特征和同上 get_executor() 成员函数将协调以指向该链的执行程序。


¹ 或任何标记,以防您的调用模型不同,例如 yield context