Boost::Asio :io_service.run() 与 poll() 或者如何在主循环中集成 boost::asio
我目前第一次尝试使用 boost::asio 进行一些简单的 tcp 网络,我已经遇到了一些我不太确定如何处理的事情。据我了解 io_service.run() 方法基本上是一个循环,它运行直到没有什么可做的,这意味着它将运行直到我释放我的小服务器对象。由于我已经设置了某种主循环,为了简单起见,我宁愿从那里手动更新网络循环,而且我认为 io_service.poll() 会做我想要的事情,有点像这样
void myApplication::update()
{
myIoService.poll();
//do other stuff
}
:似乎有效,但我仍然想知道这种方法是否有缺点,因为这似乎不是处理 boost::asios io 服务的常用方法。这是一种有效的方法还是我应该在非阻塞额外线程中使用 io_service.run() ?
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
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 io_service::poll 代替 io_service::run 是完全可以接受的。差异在 文档
请注意,如果有任何
work
留在队列中而 io_service::poll 不会表现出这种行为,它只是调用就绪的处理程序。另请注意,您需要调用 io_service::reset 在任何后续调用
io_service:run
或io_service::poll
时。Using
io_service::poll
instead ofio_service::run
is perfectly acceptable. The difference is explained in the documentationNote that
io_service::run
will block if there's anywork
left in the queuewhereas
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 toio_service:run
orio_service::poll
.一个缺点是你会形成一个繁忙的循环。
将使用 100% CPU。
myIoService.run()
将使用 0% cpu。myIoService.run_one()
可能会做你想做的事情,但如果没有什么可做的,它会阻塞。A drawback is that you'll make a busy loop.
will use 100% cpu.
myIoService.run()
will use 0% cpu.myIoService.run_one()
might do what you want but it will block if there is nothing for it to do.像这样的循环允许您轮询,不忙等待,并根据需要重置。 (我正在使用更新的
io_context
来替换io_service
。)A loop like this lets you poll, doesn't busy-wait, and resets as needed. (I'm using the more recent
io_context
that replacedio_service
.)