boost::asio 套接字 async_* 链
如何通过strand对socket执行async_*操作?我看过 Timer.5(Boost/Asio 示例),但它们仅显示如何调用用户的处理程序。当我在多线程应用程序中async_write
到套接字时,数据可能会被写入损坏。 strand
保证这些处理程序不会同时执行。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 Boost.Asio 文档:
有一个很好的例子 Boost.Asio 示例中的
strand
用法。strand
保证您的处理程序执行将同步。这意味着如果您的io_service
从多个线程执行,则strand
非常有用。它与您如何安排任务(处理程序)无关。strand
无法帮助您同时执行多个套接字读或写操作,因为内部读/写执行不能同时完成,因此应该只有一个活动的读或写异步操作。对于
读取
,您只需调用async_read
来启动读取序列,并在消耗接收到的数据后从读取处理程序中再次调用它。与在单线程环境中执行的操作相同。对于
写入
,如果有并发生产者(如果多个线程提供要写入套接字的数据),则需要一个并发队列(例如增强循环缓冲区,查找“有界缓冲区示例”)。您的写入函数从此缓冲区获取数据并将其异步写入套接字。您的写入处理程序调用您的写入函数。From Boost.Asio docs:
There's a good example of
strand
usage in Boost.Asio examples.strand
guarantees that your handler execution will be synchronized. That means thatstrand
is useful if yourio_service
is executed from multiple threads. It's not related to how you schedule your tasks (handlers).strand
cannot help you to do multiple socket read or write ops concurrently, because internal read/write execution cannot be done concurrently, so there should be just one active read or write async op.For
reads
you just callasync_read
to initiate read sequence and call it again from your read handler after consuming received data. The same that you do in single threaded environment.For
writes
if there're concurrent producers (if multiple threads provides data to be written to socket) you need a concurrent queue (e.g. boost circular buffer, look for "Bounded Buffer Example"). Your write function takes data from this buffer and async writes it to socket. Your write handler invokes your write function.如果多个线程需要在套接字上写入数据,则必须确保数据的顺序。这在
async_write()
文档。我建议维护一个消息传出队列,这与这个问题和我的答案。
If multiple threads need to write data on the socket, you will have to ensure ordering of the data. This is explicitly clear in the
async_write()
documentation.I suggest maintain an outgoing queue of messages, which is very similar to this question and my answer.