以下示例取自 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
来检索值,因此在下一个元素开始求和之前,我不知道如何在不等待第一个元素完成的情况下编写它。
最佳答案
你是对的,当前的 future
库还没有完成。我们错过的是一种指示“当 future x 准备就绪时,开始操作 f”的方法。这是一个不错的 post about that .
您可能需要一个 map/reduce 实现:在每个 future 完成后,您希望开始将其添加到累加器(reduce)。
您可以为此使用库 - 自己构建它不是很简单:)。获得关注的库之一是 RxCpp - 他们有一个 post on map/reduce .
关于c++ - 如何在不等待的情况下使用 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44353996/