c ++ 11异步延续或尝试.then()语义

dir*_*ine 16 c++ c++11 stdasync

下面的代码基于Herb Sutter关于.then()类型延续的实现想法.

  template<typename Fut, typename Work>
auto then(Fut f, Work w)->std::future<decltype(w(f.get()))>
  { return std::async([=] { w(f.get()); }); }
Run Code Online (Sandbox Code Playgroud)

这可以像auto next = then(f, [](int r) { go_and_use(r); });或类似地使用.

这是一个很好的想法,但它现在不起作用(期货只是移动而不是可复制的).我喜欢这个想法,因为它可能出现在即将推出的c ++版本中,据我所知(尽管是.then()甚至是等待.)

在让期货共享或类似之前,我想知道堆栈溢出社区会特别考虑改进和建议(甚至是共享期货)对这种实现的看法?

在此先感谢您的任何建议.

(我知道这是一个修复,直到基于标准的机制存在,因为它将花费一个线程(也许))).

ron*_*nag 7

我发现上述实现有3个问题:

  • 如果你通过它只会工作std::shared_futureFut.
  • 延续可能希望有机会处理异常.
  • 它并不总是按预期运行,因为如果你没有指定std::launch::async它可能会延迟,因此不会像人们预期的那样调用continuation.

我试图解决这些问题:

template<typename F, typename W, typename R>
struct helper
{
    F f;
    W w;

    helper(F f, W w)
        : f(std::move(f))
        , w(std::move(w))
    {
    }

    helper(const helper& other)
        : f(other.f)
        , w(other.w)
    {
    }

    helper(helper&& other)
        : f(std::move(other.f))
        , w(std::move(other.w))
    {
    }

    helper& operator=(helper other)
    {
        f = std::move(other.f);
        w = std::move(other.w);
        return *this;
    }

    R operator()()
    {
        f.wait();
        return w(std::move(f)); 
    }
};

}

template<typename F, typename W>
auto then(F f, W w) -> std::future<decltype(w(F))>
{ 
    return std::async(std::launch::async, detail::helper<F, W, decltype(w(f))>(std::move(f), std::move(w))); 
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

std::future<int> f = foo();

auto f2 = then(std::move(f), [](std::future<int> f)
{
    return f.get() * 2; 
});
Run Code Online (Sandbox Code Playgroud)