首页 > 解决方案 > C++ 异步期货没有完成

问题描述

我在 C++ 中运行多个模拟实例,我想使用期货来分发这些模拟以减少程序的运行时间。主函数runSimulation接受一个Parameters对象并返回一个结果列表(准确地说是一个双精度向量)。

如果我让一切按顺序运行,它就可以工作(但速度很慢)。如果我使用std::async,一些但不是所有未来调用会卡住并且不返回任何内容。

我的代码如下所示:

const int l = 8; // number of simulations to run
std::vector<Parameters> params = createRandomParameters(l);

std::vector<std::vector<double>> simRes;
simRes.reserve(l);

// set up the futures
std::vector<std::future<std::vector<double>>> futures;
futures.reserve(l);

// create the futures
for (int i = 0; i < l; ++i) {
    futures.push_back(std::async(std::launch::async, &runSimulation, params[i]));
}

// get the results
for (auto &fut : futures) {
    simRes.push_back(fut.get());
}

请注意,只有一些期货挂起,而其他期货按预期工作(通过查看我的系统监视器及其 CPU 利用率可以观察到这一点)。

顺序的

如果我将期货部分替换为

for (int i = 0; i < l; ++i) simRes.push_back(runSimulation(params[i]));

一切正常(但当然很慢),所以我猜错误不在模拟功能中。

延期

使用std::launch::deferred代替std::launch::async也可以,但是因为我fut.get()按顺序调用,所以执行不是并行执行的。

省略std::launch(即futures.emplace_back(std::async(&runSimulation, params[i]));导致与std::launch::async.

不幸的是,我无法使用不同的 MWE 函数重现此错误。

系统

我使用 Ubuntu 18.04.1 和gcc 7.3.0. 在 CMake 中,我指定-pthread标志并使用 C++ 17(我也尝试过 11 和 14 ...)。

知道什么可能导致这种行为或如何修复它,以便我可以在不同的内核上运行模拟吗?

标签: c++asynchronousfuture

解决方案


推荐阅读