昨天在调试项目工程的时候遇到了一个现象:
因为,我在ocx和服务器之间做了一个tcp连接,为了检测连接是否断开,所以手动做了一个保活,即,每隔一段时间就给对方发送一个保活请求。当检测到连接断开后,ocx启动重新连接!问题来了,当重新连接后,程序不会退出重连,而是不断的连接。经过排查,问题的原因是:asio.run()的使用问题。
查询asio官网,在run函数的说明下面,有这么一句话:
The
run()
function must not be called from a thread that is currently calling one of run()
, run_one()
, poll()
or poll_one()
on the same io_service
object.这句话的意思是,在一个io_service的线程中,如果已经调用过了run()
, run_one()
, poll()
or poll_one(),那么久不能在调用run了。
但是,我们又必要要run函数在宝石io_service的正常运行,怎么办呢?于是,我看到了reset()函数。
This function must be called prior to any second or later set of invocations of the run()
,
这也就是说,在我们第二次调用run函数之前,我们必须首先调用reset()函数,因为在我们第一次调用run结束之后,stopped()是返回true的,所以,如果我们第二次直接调用run,那么run是会直接退出的,reset会让stoped()返回false。