c++ - 发生哪些线程异步操作

标签 c++ multithreading boost boost-asio

阅读 asio 的文档后,我很清楚完成处理程序是由调用 io_service 的 io.run() 方法的线程之一调用的。但是,我不清楚读/写异步方法发生在哪个线程。是我调用方法的线程还是调用 io.run() 方法的线程之一?或者,在最后一种情况下,库是否会在幕后创建另一个线程并执行操作?

最佳答案

I/O 操作将在启动 async_* 函数中尝试。如果满足操作的完成条件或发生错误,则操作完成并且完成处理程序将发布到 io_service 中。否则,操作未完成,它将被排队到 io_service,其中一个应用程序线程运行 io_service 的函数 poll()poll_one()run()run_one() 执行底层 I/O 操作。在这两种情况下,完成处理程序都由处理 io_service 的线程调用。

async_write()文档指出异步操作可能会立即完成:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

此行为也记录在 Requirements on Asynchronous Operations 中文档:

When an asynchronous operation is complete, the handler for the operation will be invoked as if by:

  • Constructing a bound completion handler bch for the handler ...
  • Calling ios.post(bch) to schedule the handler for deferred invocation ...

This implies that the handler must not be called directly from within the initiating function, even if the asynchronous operation completes immediately.


这是一个完整的例子demonstrating这种行为。其中,socket1socket2 相连。最初,socket2 没有可用数据。但是,在调用 async_write(socket1, ...) 之后,即使 io_service 尚未运行,socket2 也有数据:

#include <boost/asio.hpp>

constexpr auto noop = [](auto&& ...){};

int main()
{
  using boost::asio::ip::tcp;
  boost::asio::io_service io_service;

  // Create all I/O objects.
  tcp::acceptor acceptor{io_service, {{}, 0}};
  tcp::socket socket1{io_service};
  tcp::socket socket2{io_service};

  // Connect sockets.
  acceptor.async_accept(socket1, noop);
  socket2.async_connect(acceptor.local_endpoint(), noop);
  io_service.run();
  io_service.reset();

  // Verify socket2 has no data.
  assert(0 == socket2.available());

  // Initiate an asynchronous write.  However, do not run
  // the `io_service`.
  std::string data{"example"};
  async_write(socket1, boost::asio::buffer(data), noop);

  // Verify socket2 has data.
  assert(0 < socket2.available());
}

关于c++ - 发生哪些线程异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273216/

相关文章:

c++ - 如何查看C++宏的内容?

Java多线程错误 `java.lang.IllegalMonitorStateException`

c++ - 如何在托管共享内存段中创建同步机制?

c++ - boost 程序选项在从命令行读取时更改数据(这是 boost 中的错误吗?)

c++ - Mac OS X 和静态 boost 库 -> std::string 失败

c++ - 在 SDL 中旋转 Sprite 图像

c++ - 为什么程序在堆栈展开后无法到达正确的返回指令?

c++ - 我们可以假设以下任何一对浮点算术语句总是产生相同的结果吗?

c# - 跨线程读取值不重要的变量

java - 为什么线程池独立地而不是并发地执行任务?