asio :: async_write和strand

Iwa*_*Iwa 3 c++ multithreading boost boost-asio

asio::async_write(m_socket, asio::buffer(buf, bytes),
                custom_alloc(m_strand.wrap(custom_alloc(_OnSend))));
Run Code Online (Sandbox Code Playgroud)

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

Tan*_*ury 8

使用以下代码:

asio::async_write(stream, ..., custom_alloc(m_strand.wrap(...)));
Run Code Online (Sandbox Code Playgroud)

对于此组合操作,如果满足以下所有条件,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(...)));
    
    Run Code Online (Sandbox Code Playgroud)
  • 返回类型custom_alloc是:

    • 返回的确切类型 strand::wrap()

      template <typename Handler> 
      Handler custom_alloc(Handler) { ... }
      
      Run Code Online (Sandbox Code Playgroud)
    • 适合链调用的自定义处理程序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};
      }
      
      Run Code Online (Sandbox Code Playgroud)

这个答案对绞线的详细信息,以及这个答案的详细信息asio_handler_invoke.

  • 请参阅我对您的回答的评论。必须这样,否则各种事情都行不通,从 SSL 开始。如果套接字同时变得可读和可写,则两个线程(一个为异步读取执行组合操作,另一个为异步写入执行一个操作)可能同时访问相同的 SSL 上下文,并且程序将崩溃。这是 ASIO 的一个核心特性,它使各种事情都能正常工作。转到[此处](http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/overview/core/strands.html) 并阅读以“在组合的情况下”开头的段落。 (2认同)