gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:07:39 25 4
gpt4 key购买 nike

阅读 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com