使用boost :: future :: then在主线程中执行

时间:2014-08-15 13:28:50

标签: c++ multithreading boost

编译器:mingw4.8.2 os:win7 32bits

#define BOOST_THREAD_PROVIDES_FUTURE
#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION

#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>

#include <iostream>
#include <string>

int main()
{

    std::cout<<"main thread id : "<<boost::this_thread::get_id()<<std::endl;
    boost::future<int> f1 = boost::async(boost::launch::async, []()
    {
        std::cout<<"async thread id : "<<boost::this_thread::get_id()<<std::endl;
        return 123;
    });
    boost::future<std::string> f2 = f1.then(boost::launch::deferred, [](boost::future<int> f)
    {
            std::cout<<"then id : "<<boost::this_thread::get_id()<<std::endl;
            return boost::lexical_cast<std::string>(f.get());
    });

    f2.wait();
}

结果:

main thread id : 3758
async thread id : 33b4
then id : 3824

如何让lambda表达式传入“then”在主线程中运行?无论如何要求它在主线程中运行?如果通过boost没有简单的方法可以在Qt的帮助下进行异步等待(当未来准备就绪时,发出信号并在主线程中运行该函数)?

编辑:f1.then的目的

boost :: async可能会运行一些繁重的任务,如果我不让这个任务在另一个线程上运行,它很可能会阻止gui。任务完成后,我想告诉gui并执行一些与之相关的动作gui,这就是我使用f1.then的原因,因为这样我就不需要阻止这个功能了。

修改:看起来像延期可以工作

//cout has not thread safe guarantee, but adding mutex at here will cause dead lock...
std::cout<<"main thread id : "<<boost::this_thread::get_id()<<std::endl;
auto f1 = boost::async(boost::launch::async, [&]()
{
    boost::this_thread::sleep(boost::posix_time::seconds( 5 ));
    std::cout<<"async thread id : "<<boost::this_thread::get_id()<<std::endl;
    return 123;
});
auto f2 = f1.then(boost::launch::deferred, [&](decltype(f1) f)
{
        std::cout<<"then result : "<<f.get()<<std::endl;
        std::cout<<"then id : "<<boost::this_thread::get_id()<<std::endl;
        return std::string("result get");
});


for(size_t i = 0; i != 50; ++i){
    std::cout<<i<<std::endl;
}

f2.wait();

1 个答案:

答案 0 :(得分:4)

template<typename F>
 future<typename boost::result_of<F( future&)>::type>
then(F&& func); // EXTENSION
template<typename S, typename F>
 future<typename boost::result_of<F( future&)>::type>
then(S& scheduler, F&& func); // EXTENSION NOT_YET_IMPLEMENTED
template<typename F>
 future<typename boost::result_of<F( future&)>::type>
then(launch policy, F&& func); // EXTENSION
来自future documentation

。你应该使用第三版的功能。

f1.then(boost::launch::deferred, ...)