[英]How to use a future without waiting for it?
以下示例取自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;
}
如何在不等待的情況下使用future
的結果? 即我想做這樣的事情:
int sum = 0;
for(auto &e : futures) { sum += someLengthyCalculation(e.get()); }
我可以將對future
的引用傳遞給someLengthyCalculation
,但在某些時候我必須調用get
來檢索值,因此我不知道如何編寫它而不等待第一個元素完成,然后下一個元素可以開始求和。
期貨的設計適用於這種解決方案,您可以創建更多代表計算值的期貨:
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(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.