下面的例子是从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
检索值,因此,我不知道怎么写而不用等待第一个元素完成,然后下一个可以开始求和。
您是否在寻找像'then'和'when_all'或'when_any'延续? – kreuzerkrieg