emulate std::async with std::launch::sync?

emulate std::async with std::launch::sync?

本文关键字:std sync launch async emulate with      更新时间:2023-10-16

我想实现这样的方法:

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

我知道boost::promiseboost::packaged_taskset_wait_callback,但是,由于返回的future引用了其中一个,这将不起作用吗?

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

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

可以使用set_wait_callback,您只需要动态分配promise,并在设置值后在回调中删除它:

#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;
}

您可以使用此票证的代码:https://svn.boost.org/trac/boost/ticket/4710