我想实现这样的方法:
boost::unique_future<int> foo()
{
return defer([=] // call this lambda on boost::unique_future<int>::get();
{
return prime(10);
});
}
我知道boost::promise
和boost::packaged_task
以及set_wait_callback
,但是由于返回的未来会引用其中任何一项都不起作用?
我知道有std::async
和std::launch::sync
,但如何使用boost和vs2010来模拟它呢?
std::unique_future<int> foo()
{
return std::async(std::launch::sync, [=]
{
return prime(10);
});
}
答案 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