c++ - 多重延续链接 : boost. future 展开。怎么做

标签 c++ c++11 boost concurrency continuations

我正在使用 boost.future<T>有延续,在 boost 1.56 中。

我有一个返回 future 的 API,我想在 延续。所以理论上,我需要 .unwrap链接之前的 future 第二次续集。

所以我做了以下事情:

auto result = api_returns_future().then([](boost::future<R> && result) {
                    do_something_with_result();

                    //Note I could call .get() here, but I don't
                    return api_returns_future();
              }).unwrap() //Now I unwrap the future here
              .then([](boost::future<R> && result) { ... });

也就是说,我有:

  1. future<R>::then
  2. 在第一个继续中,我从 lambda 返回一个返回 boost::future<R> 的 API 调用。然后我打开它。
  3. 之后我想附加另一个延续,但从未调用过这个延续。

问题:

  1. 在第一个延续中这样做是正确的:return api_returns_future().get() (请注意,我直接从 continuation 内部调用 .get() 并放弃展开?这种替代方案是否对我的代码的异步性有一些缺点?

编辑:经过更多研究后,我更新了问题以更好地反射(reflect)我想问的问题。

谢谢

最佳答案

如果您查看 boost docs , 有一个如何使用 then() 的例子:

future<int> f1 = async([]() { return 123; });
future<string> f2 = f1.then([](future<int> f) { 
    return f.get().to_string(); // here .get() won't block 
});

请注意,then 也将其 lambda 的结果包装在 future 中。现在在你的情况下,你的 lambda 返回一个 future ,所以作为第一步,你必须写:

auto result = api_returns_future().then([](future<R> result) {
    // stuff
    return api_returns_future();
}).then([](future<future<R>> result2) {
//         ^^^^^^^^^^^^^^^^^
    // other stuff
});

但出于这个原因,文档还指出有一个 unwrap move constructor :

Unwrap Move Constructor - EXTENSION

 future( future< future<R>>& other); // EXTENSION

Postconditions
this->get_state() returns the value of other->get_state() prior to the call. other->get_state() returns boost::future_state::uninitialized. The associated shared state is now unwrapped and the inner future shared state is associated with *this. other is not associated with any shared state, ! other.valid().

因此我希望您能够编写以下内容:

auto result = api_returns_future().then([](future<R> result) {
    // stuff
    return api_returns_future();
}).then([](future<R> result2) {
//         ^^^^^^^^^
    // other stuff
});

因为库会自己处理解包。

关于c++ - 多重延续链接 : boost. future 展开。怎么做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28103104/

相关文章:

c++ - 循环一个函数

c++ - 在集合中寻找一个值

c++ - 什么时候初始化 `thread_local` 全局变量?

C++ Lambda : Difference between "mutable" and capture-by-reference

c++ - Boost ASIO 将 X 字节同步读入 vector

c++ - 为什么我在使用 boost::asio::null_buffers 时无法获取发送端点?

另一个基类中的c++抽象类实现

c++ - 通过编写包装器将 RogueWave 替换为标准库

c++ - Widget&& rhs 是左值还是右值引用

c++ - Boost::C++ 数据复制的信号