asio::async_write 和链

2021-12-24 00:00:00 multithreading c++ 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?)

Does this code guarantee that all asynchronous operation handlers(calls to async_write_some) inside async_write are called through strand? (or it's just for my_handler?)

推荐答案

使用以下代码:

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

对于这个组合操作,如果以下所有条件都为真,所有对 stream.async_write_some() 的调用都将在 m_strand 内调用:

For this composed operation, all calls to stream.async_write_some() will be invoked within m_strand if all of the following conditions are true:

  • 发起的 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 的详细信息.

    See this answer for more details on strands, and this answer for details on asio_handler_invoke.

    相关文章