boost :: asio :: io_service:在等待将来时将控制权返回给IO服务的运行 [英] boost::asio::io_service: return control to IO service's run while waiting for future

查看:85
本文介绍了boost :: asio :: io_service:在等待将来时将控制权返回给IO服务的运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,可以通过IO服务中的第三方进行调用.我的方法应该返回一个布尔值.但是,我需要将另一个任务发布到同一IO服务,并等待其完成才知道结果.等待其他任务完成时,如何将控制返回到IO循环?

I have a method that gets called via a third party from IO service. My method is supposed to return a boolean. However, I need to post another task to the same IO service, and wait for it to complete before I know the result. How can I return control to the IO loop while I wait for the other task to finish?

(我可以添加多个线程,但随后可能会多次调用我的方法,但最终仍然会导致死锁)

(I can add multiple threads, but then there could be multiple calls to my methods, and you'd still end up with a deadlock)

之前调用图:

<thread>    io_service               third_party    my_stuff
   |            |                        |             |
   |---run----->|                        |             |
   |            |-->some_posted_method-->|             |
   |            |                        |--callback-->|
   |            |                        |<--boolean---|
   |            |(next task)             |             |
   |            |                        |             |

首选调用图:

<thread>    io_service               third_party    my_stuff
   |            |                        |             |
   |---run----->|                        |             |
   |            |-->some_posted_method-->|             |
   |            |                        |--callback-->|
   |            |<----some_way_to_return_control-------|
   |            |(next task)             |             |
   |            |--------some_kind_of_resume---------->|
   |            |                        |<--boolean---|
   |            |                        |             |

推荐答案

就像 Tanner Sansbury 所述,您可以从事件处理程序中调用poll_one,它将执行可用的处理程序.

Like Tanner Sansbury mentioned, you can call poll_one from your event handler, and it will execute the available handlers.

请记住,您必须调用poll_one,因为如果继续添加新的处理程序,则不能保证返回poll.而且,由于poll_one可能尚未准备好要执行的处理程序,因此您可能需要添加睡眠以防止繁忙的等待.我的代码最终如下所示:

Mind that you have to call poll_one, since poll is not guaranteed to return if new handlers keep being added. And since poll_one may not have a handler ready to execute yet, you may want to add a sleep to prevent busy waiting. My code ended up like this:

while( !syncDone ) {
    boost::system::error_code  ec;

    int handlersExecuted = ioService.poll_one(ec);
    if( ec ) {
        //Not sure what error there could be, log it
    }

    if( 0 == handlersExecuted ) {
        std::this_thread::sleep_for(
            std::chrono::milliseconds(10)
        );
    }
}

这篇关于boost :: asio :: io_service:在等待将来时将控制权返回给IO服务的运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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