Boost::Asio : io_service.run() vs poll() 或者我如何在 mainloop 中集成 boost::asio
我目前第一次尝试将 boost::asio 用于一些简单的 tcp 网络,但我已经遇到了一些我不确定如何处理的问题.据我了解 io_service.run() 方法基本上是一个循环,它会一直运行直到没有其他事情要做,这意味着它会一直运行直到我释放我的小服务器对象.由于我已经设置了某种主循环,为了简单起见,我宁愿从那里手动更新网络循环,而且我认为 io_service.poll() 会做我想做的事,有点像这样:
I am currently trying to use boost::asio for some simple tcp networking for the first time, and I allready came across something I am not really sure how to deal with. As far as I understand io_service.run() method is basically a loop which runs until there is nothing more left to do, which means it will run until I release my little server object. Since I allready got some sort of mainloop set up, I would rather like to update the networking loop manually from there just for the sake of simplicity, and I think io_service.poll() would do what I want, sort of like this:
void myApplication::update()
{
myIoService.poll();
//do other stuff
}
这似乎有效,但我仍然想知道这种方法是否有缺点,因为这似乎不是处理 boost::asios io 服务的常用方法.这是一种有效的方法还是我应该在非阻塞额外线程中使用 io_service.run() ?
This seems to work, but I am still wondering if there is a drawback from this method since that does not seem to be the common way to deal with boost::asios io services. Is this a valid approach or should I rather use io_service.run() in a non blocking extra thread?
推荐答案
使用 io_service::poll
而不是 io_service::run
是完全可以接受的.文档
Using io_service::poll
instead of io_service::run
is perfectly acceptable. The difference is explained in the documentation
也可以使用 poll() 函数分派准备好的处理程序,但是没有阻塞.
The poll() function may also be used to dispatch ready handlers, but without blocking.
请注意,io_service::run
将阻止任何work
留在队列中
Note that io_service::run
will block if there's any work
left in the queue
工作类用于通知io_service 工作开始时完成.这确保了io_service 对象的 run() 函数工作正在进行时不会退出,并且它确实在没有时退出剩下的未完成的工作.
The work class is used to inform the io_service when work starts and finishes. This ensures that the io_service object's run() function will not exit while work is underway, and that it does exit when there is no unfinished work remaining.
而 io_service::poll
没有表现出这种行为,它只是调用准备好的处理程序.另请注意,您需要调用 io_service::reset 对 io_service:run
或 io_service::poll
的任何后续调用.
whereas io_service::poll
does not exhibit this behavior, it just invokes ready handlers. Also note that you will need to invoke io_service::reset on any subsequent invocation to io_service:run
or io_service::poll
.
相关文章