c++ - 提升 Asio : Calling sync read while an async_read is pending on the same socket

标签 c++ networking network-programming boost-asio

我一直在使用 async_read() 从套接字读取数据。但是,在某些事件中,我必须通过同一个套接字同步发送数据,并在除上述 async_read 之外的事件处理程序中等待 ACK(也是同步的)。我正在等待同步 read() 调用中的 ACK。 (请注意,我不是在谈论 async_read_someread_some)。

async_read() 在后台挂起时调用同步 read() 是否可以?

是否有可能 async_read() 已经将一半消息接收到其内部缓冲区中,而我的同步 read() 将返回下半部分消息?

如何优雅地取消/暂停 async_read()(不丢失任何数据),以便同时安全地调用 sync read()

最佳答案

你不能那样做。

引自 boost 文档:

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

作为普通的 boost::asio::read 也是一个组合的读取操作,这可能会调用 UB。

要优雅地停止您的async_read,您可以调用cancel (*) 尽管如此,在混合异步和正常操作时应该考虑您的设计。我建议从 async_read 回调处理程序发送 ACK。

(*) 请注意,取消有一些缺点,如链接中所述。一个是例如`取消可能会被忽略。

关于c++ - 提升 Asio : Calling sync read while an async_read is pending on the same socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873771/

相关文章:

java - Apache mina 中的 session 管理/监控

security - 如何唯一标识一个网络?

c++ - 使用 protobuf 反射在 C++ 中获取 bool 字段描述符

java - 只要 ArrayList 中有元素,如何使用线程执行功能?

java - Jboss Netty - 无法连续发送数据?

c++ - Windows 中 SO_RCVBUF 的最大值?

java - 构建网络拓扑

c++ - VC++ 和 windows.h 中的 BYTE typedef

C++ unique_ptr 移动构造函数

c++ - 将 C++ 代码编译为静态库 (.a)