使用std :: launch :: sync模拟std :: async?

时间:2012-01-21 23:08:20

标签: c++ visual-studio-2010 boost future

我想实现这样的方法:

boost::unique_future<int> foo()
{
    return defer([=] // call this lambda on boost::unique_future<int>::get();
    {
         return prime(10);
    });
}

我知道boost::promiseboost::packaged_task以及set_wait_callback,但是由于返回的未来会引用其中任何一项都不起作用?

我知道有std::asyncstd::launch::sync,但如何使用boost和vs2010来模拟它呢?

std::unique_future<int> foo()
{
    return std::async(std::launch::sync, [=] 
    {
         return prime(10);
    });
}

2 个答案:

答案 0 :(得分:2)

可以使用set_wait_callback,您只需动态分配承诺,并在设置值后在回调中将其删除:

#include <boost/thread.hpp>
#include <iostream>

void callback(boost::promise<int>&p) {
    std::cout<<"callback"<<std::endl;
    p.set_value(42);
    delete &p;
}

boost::unique_future<int> f()
{
    boost::promise<int> *p=new boost::promise<int>;
    p->set_wait_callback(callback);
    return p->get_future();
}

int main()
{
    boost::unique_future<int> uf(f());
    std::cout<<"main()"<<std::endl;
    int val=uf.get();
    std::cout<<"val="<<val<<std::endl;
}

答案 1 :(得分:0)

您可以使用此故障单的代码:https://svn.boost.org/trac/boost/ticket/4710