简体   繁体   English

永远运行boost asio io_service

[英]Run boost asio io_service forever

I call boost::asio::io_service::run() and it returns immediately since it has no jobs to do. 我调用boost::asio::io_service::run()并立即返回,因为它没有任何工作要做。
A different thread will queue work later on, but I don't want the run thread to exit. 一个不同的线程将在稍后排队工作,但我不希望run线程退出。
On solution is to busy wait on run: 解决方案是忙于等待运行:

while(true) service.run();

But that would waste CPU when there is no work to do. 但是,当没有工作要做时,这会浪费CPU。
Another way is to wait on an event that is raised every time something is queued to the service. 另一种方法是等待每次排队等待服务时引发的事件。
This way has a race: If one thread stops doing work and then a second thread posts work and raises the event before the first has a chance to wait on it, the first would wait forever. 这种方式有一个竞争:如果一个线程停止工作,然后第二个线程发布工作并在第一个有机会等待它之前引发事件,第一个将永远等待。
I would rather avoid that and have the service know when there is work to do. 我宁愿避免这种情况,并在有工作要做时知道服务。
Is it possible to do something like: 有可能做这样的事情:

while(true)
{
    service.wait_for_work();
    service.run();
}

为此目的存在io_service::work对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM