如何在不等待的情况下使用未来?
问题描述:
下面的例子是从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
库尚未完成。我们错过的是一种表示'未来x准备就绪,开始操作f'的方式。这是一个不错的post about that。
你可能想要的是一个map/reduce实现:在每个将来完成时,你想开始将它添加到累加器(reduce)中。
您可以使用库 - 它是不是很简单建立它自己:)。其中一个正在获得牵引力的图书馆是RxCpp--它们有post on map/reduce。
答
期货的设计适合于这种解决方案,让您创建一个表示的计算值更期货:
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(); }
+0
也许这就是更多OP的答案。提示:std ::将期货转换为calculate_futures以更好地表达意图。 – xtofl
您是否在寻找像'then'和'when_all'或'when_any'延续? – kreuzerkrieg