1

我想与 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)

我想知道为什么。我不应该能够存储未来的对象吗?

4

1 回答 1

6

handles使用 5 个默认构造的元素初始化了数组,然后又在其中放置了 5 个元素。它现在有 10 个元素,其中前 5 个是默认构造的,因此不与任何等待相关联。

不要创建包含 5 个元素的向量。我认为您试图为 5 个元素保留空间- 这可以通过reserve在构造向量后调用来完成。

于 2021-03-31T11:20:04.207 回答