中断boost :: asio同步读? [英] Interrupt boost::asio synchronous read?

查看:132
本文介绍了中断boost :: asio同步读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用asio同步套接字通过TCP从后台线程读取数据。这封装在一个服务器类中。

I'm using asio synchronous sockets to read data over TCP from a background thread. This is encapsulated in a "server" class.

但是,当调用此类的析构函数时,我希望线程退出。
问题是调用任何读取函数都会阻塞,因此线程不能轻易终止。在Win32中有一个API为: WaitForMultipleObjects 这将做我想要的。

However, I want the thread to exit when the destructor of this class is called. The problem is that a call to any of the read functions does block, so the thread cannot be easily terminated. In Win32 there is an API for that: WaitForMultipleObjects which would do exactly what I want.

与boost相似的效果?

How would I achieve a similar effect with boost?

推荐答案

我没有找到任何简单的方法。据推测,有办法取消win32 IOCP,但它不能在Windows XP上正常工作。 MS确实修复了windows vista和7.推荐的方法来取消asio async_read async_write 是关闭套接字

I have found no easy way to do this. Supposedly, there are ways to cancel win32 IOCP, but it doesn't work well on windows XP. MS did fix it for windows vista and 7. The recommended approach to cancel asio async_read or async_write is to close the socket.


  • [destructor]注意我们想要拆卸


  • [destructor]等待完成处理程序

  • [destructor] note that we want to teardown
  • [destructor] close the socket
  • [destructor] wait for completion handlers

[完成]套接字关闭,通知析构函数完成处理程序完成。

[completion] if tearing down and we just failed because the socket closed, notify the destructor that the completion handlers are done.

如果你选择实现这一点,要小心。关闭套接字很简单。 等待完成处理程序然而是巨大的缩写。

Be careful if you choose to implement this. Closing the socket is pretty straight forward. 'wait for completion handlers' however is huge understatment. There are several subtle corner cases and race conditions that could occur when the server's thread and its destructor interact.

这是微妙的,我们构建一个完成包装器(类似于 io_service :: strand 只是为了同步处理所有待处理的完成回调。

This was subtle enough that we build a completion wrapper (similar to io_service::strand just to handle synchronously canceling all pending completion callbacks.

这篇关于中断boost :: asio同步读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆