ASIO IO 完成回调顺序与实际 IO 操作的顺序

ASIO IO completion callbacks order vs the order of actual IO operations

从实现中可以明显看出,在单线程模式下 运行 时,IO 完成回调的调用顺序与实际 IO 操作相同,但我找不到相应的文档部分来确认.它是否明确地写在任何地方?

io-object 类 上所有 async_xxx 方法的文档中有这样一段话:

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().

正在查看 boost::asio::io_service::post() 的文档...

This function is used to ask the io_service to execute the given handler, but without allowing the io_service to call the handler from inside this function.

The io_service guarantees that the handler will only be called in a thread in which the run(), run_one(), poll() or poll_one() member functions is currently being invoked.

这就是您的全部保证。

如果您的代码依赖于异步事件的时间顺序,那么它就不是异步代码。

甚至 run_one() 的文档也无法保证 它将调度哪个 处理程序:

The run_one() function blocks until one handler has been dispatched, or until the io_service has been stopped.

如果您必须对单个异步操作(例如读取)进行排序,那么您有义务:

  • 从第一个处理程序启动第二个操作,或者

  • 在操作的处理程序未完成时保持标志设置,并且仅在标志为 false 时才启动另一个操作。