asio :: async_write和strand

时间:2016-03-15 15:53:12

标签: c++ multithreading boost boost-asio

asio::async_write(m_socket, asio::buffer(buf, bytes),
                custom_alloc(m_strand.wrap(custom_alloc(_OnSend))));

此代码是否保证async_write中的所有异步操作处理程序(对async_write_some的调用)都是通过strand调用的? (或者仅仅是 my_handler ?)

2 个答案:

答案 0 :(得分:8)

使用以下代码:

asio::async_write(stream, ..., custom_alloc(m_strand.wrap(...)));

对于此组合操作,如果满足以下所有条件,则将在stream.async_write_some()内调用m_strand的所有调用:

  • 发起async_write(...)来电正在m_strand()中运行:

    assert(m_strand.running_in_this_thread());
    asio::async_write(stream, ..., custom_alloc(m_strand.wrap(...)));
    
  • custom_alloc的返回类型是:

    • strand::wrap()

      返回的确切类型
      template <typename Handler> 
      Handler custom_alloc(Handler) { ... }
      
    • 自定义处理程序,适用于asio_handler_invoke()的链调用:

      template <class Handler>
      class custom_handler
      {
      public:
        custom_handler(Handler handler)
          : handler_(handler)
        {}
      
        template <class... Args>
        void operator()(Args&&... args)
        {
          handler_(std::forward<Args>(args)...);
        }
      
        template <typename Function>
        friend void asio_handler_invoke(
          Function intermediate_handler,
          custom_handler* my_handler)
        {
          // Support chaining custom strategies incase the wrapped handler
          // has a custom strategy of its own.
          using boost::asio::asio_handler_invoke;
          asio_handler_invoke(intermediate_handler, &my_handler->handler_);
        }
      
      private:
        Handler handler_;
      };
      
      template <typename Handler>
      custom_handler<Handler> custom_alloc(Handler handler)
      {
        return {handler};
      }
      

有关线索的详情,请参阅this答案;有关asio_handler_invoke的详细信息,请参见this答案。

答案 1 :(得分:3)

UPD:这个答案是错误的=)对于任何有兴趣的人,您都可以在评论的尾部查看详细信息,感谢 Tanner Sansbury

没有。这可以保证您的完成处理程序将通过 strand 锁定进行调用。这不包括对async_write_some的调用。

此外,boost :: asio没有类似&#34;写队列&#34;并且您需要管理async_write次来电以防止撰写混合内容。

相关问题