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

时间:2017-06-04 12:16:43

标签: c++ asynchronous future

以下示例取自C++ async tutorial

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

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

  int sum = 0;
  for(auto &e : futures) { sum += someLengthyCalculation(e.get()); }

我可以将对future的引用传递给someLengthyCalculation,但在某些时候我必须调用get来检索值,因此我不知道如何编写它而无需等待对于第一个元素完成,在下一个元素开始求和之前。

2 个答案:

答案 0 :(得分:4)

您是对的,目前的future库尚未完成。我们想念的是一种表示'未来x准备就绪,开始运行f'的方法。这是一个不错的post about that

你可能需要的是map / reduce实现:在每个未来完成时,你想开始将它添加到累加器(reduce)。

你可以使用一个库 - 自己构建它并不是很简单:)。其中一个获得牵引力的图书馆是RxCpp--他们有一个post on map/reduce

答案 1 :(得分:1)

期货的设计适用于这种解决方案,您可以创建更多代表计算值的期货:

  std::vector<std::future<int>> calculated_futures;

  for (auto &e : futures) {
      calculated_futures.push_back(
          std::async([&e]{ return someLengthyCalculation(e.get()); })
      );
  }

  int sum = 0;
  for(auto &e : calculated_futures) { sum += e.get(); }
相关问题