如何在不等待的情况下使用未来?

for*_*818 6 c++ asynchronous future

以下示例取自C++异步教程:

#include <future>
#include <iostream>
#include <vector>

int twice(int m) { return 2 * m; }

int main() {
  std::vector<std::future<int>> futures;
  for(int i = 0; i < 10; ++i) { futures.push_back (std::async(twice, i)); }

  //retrive and print the value stored in the future
  for(auto &e : futures) { std::cout << e.get() << std::endl; }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何在future不等待的情况下使用a的结果?即我想做这样的事情:

  int sum = 0;
  for(auto &e : futures) { sum += someLengthyCalculation(e.get()); }
Run Code Online (Sandbox Code Playgroud)

我能传递给一个参考futuresomeLengthyCalculation,但在某些时候我不得不打电话get来检索值,因此,我不知道如何把它写而不被完成,在下单前可以开始总结等待第一个元素.

xto*_*ofl 4

你是对的,当前的future库尚未完成。我们缺少的是一种指示“当未来 x 准备好时,开始操作 f”的方法。这是一篇关于此的好文章

您可能想要的是映射/归约实现:在每个 future 完成后,您希望开始将其添加到累加器(归约)。

您可以使用一个库来实现这一点 - 自己构建它并不是很简单:)。RxCpp 是越来越受欢迎的库之一 - 他们在 map/reduce 上有一篇文章