簡體   English   中英

C++ 將 std::future 形式 std::async 存儲在向量中並等待所有人

[英]C++ storing std::future form std::async in vector and wating for all

我想與 std::async 並行執行幾項任務,然后等到所有期貨都完成。

void update() {
  // some code here
}

int main() {

  std::vector<std::future<void>> handles(5);

  for (int i = 0; i < 5; ++i) {
    auto handle = std::async(std::launch::async, &update);
    handles.emplace_back(std::move(handle));
  }

  for (auto& handle : handles) {
    handle.wait();
  }

  return 0;
}

但是在執行程序時,我得到一個std::future_error拋出:

terminate called after throwing an instance of 'std::future_error'
  what():  std::future_error: No associated state
Aborted (core dumped)

我想知道為什么。 我不應該能夠存儲未來的對象嗎?

您使用 5 個默認構造的元素初始化了您的handles數組,然后又在其中放置了 5 個。 它現在有 10 個元素,其中前 5 個是默認構造的,因此不與任何等待相關聯。

不要創建包含 5 個元素的向量。 我認為您試圖為 5 個元素保留空間- 這可以通過在構造向量后調用reserve來完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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