c++ - 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 ...)。
知道什么可能导致这种行为或如何修复它,以便我可以在不同的内核上运行模拟吗?
解决方案
推荐阅读
- java - java对象锁定和监视器创建如何在JVM内部发生
- python-3.x - 类播放器 - 动画停止第一帧
- python - 我如何检查python中的键位
- c# - 在 UWP Template10 App 中,后退按钮总是返回到起始页
- c++ - 如何擦除向量元素中没有特定字符的元素
- node.js - 使用 Telegram Bot API 检索受邀用户
- javascript - 由于 JavaScript 无休止的垃圾收集,IE 冻结
- c# - 是否可以在 C# 中创建非固定大小的数组?
- google-bigquery - 复制仅覆盖源表中的分区的分区 bigquery 表
- python - 使用 zip 命令从列表列表中获取所有列表的最后一个元素