簡體   English   中英

如何在不等待的情況下使用未來?

[英]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來檢索值,因此我不知道如何編寫它而不等待第一個元素完成,然后下一個元素可以開始求和。

你是對的,目前future庫尚未完成。 我們想念的是一種表示'未來x准備就緒,開始運行f'的方法。 關於這一點,這是一篇不錯的帖子

你可能想要的是map / reduce實現:在每個未來的完成時,你想要開始將它添加到累加器(reduce)。

你可以使用一個庫 - 自己構建它不是很簡單:)。 其中一個獲得牽引力的圖書館是RxCpp--他們在地圖上有一個帖子/減少

期貨的設計適用於這種解決方案,您可以創建更多代表計算值的期貨:

  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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM