首页 > 解决方案 > boost::asio::strand 和 boost::asio::io_context::strand 之间的区别

问题描述

我想使用 strand 序列化 http post 请求,以避免重叠写入网络。

我的方法是使用发送数据的回调poststrand对象调用方法,如以下代码所示:

void Send(
   boost::beast::http::request<boost::beast::http::string_body> &req) {
  strand_.post([=]() {
      ...
      boost::beast::http::write(stream_, req);
      ...
  }

但是,通过查看一些示例,我注意到两种类型的链定义:

boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::io_context::strand strand_;

知道每种类型之间有什么不同吗?

标签: c++boostasio

解决方案


他们之间其实并没有太大的区别。事实上,它们共享大量代码,这表明一个是从另一个创建的。

请参阅此处的差异(bosst 1.67)。

但是,boost::asio::strandes 是一个最初打算用于的类模板asio::io_service

template <typename Executor>;
class strand
{
public:
  /// The type of the underlying executor.
  typedef Executor inner_executor_type;

  /// Default constructor.
  /**
   * This constructor is only valid if the underlying executor type is default
   * constructible.
   */
  strand()
    : executor_(),
      impl_(use_service<detail::strand_executor_service>(
            executor_.context()).create_implementation())
  {
  }

该类boost::asio::io_context::strand不是类模板并且绑定到类boost::asio::io_context

class io_context::strand
{
public:
  /// Constructor.
  /**
   * Constructs the strand.
   *
   * @param io_context The io_context object that the strand will use to
   * dispatch handlers that are ready to be run.
   */
  explicit strand(boost::asio::io_context&amp; io_context)
    : service_(boost::asio::use_service&lt;
        boost::asio::detail::strand_service&gt;(io_context))
  {
    service_.construct(impl_);
  }

推荐阅读