c++ - OpenMP - 将结果存储在向量中
问题描述
我想使用 OpenPM 并行化具有多次迭代的 for 循环。结果应存储在向量中。
for (int i=0; i<n; i++)
{
// not every iteration produces a result
if (condition)
{
results.push_back (result_value);
}
}
这不能与#pragma omp parallel for
.
那么实现这一目标的最佳实践是什么?
是否有可能为每个线程使用单独的结果向量,然后在最后组合所有结果向量?结果的顺序并不重要。
那样的东西不实用,因为它占用了很多空间
int *results = new int[n];
for (int i=0; i<n; i++)
{
// not every iteration produces a result
if (condition)
{
results[i] = result_value;
}
}
// remove all unused slots in results array
解决方案
选项 1:如果每次迭代在将元素添加到向量之前花费大量时间,则可以将 保持push_back
在关键区域中:
for (int i=0; i<n; i++)
{
// not every iteration produces a result
if (condition)
{
#pragma omp critical
results.push_back (result_value);
}
}
如果线程主要忙于除 之外的其他事情push_back
,那么临界区的开销就会很小。
选项 2:如果与同步开销相比迭代太便宜,您可以让每个向量填充一个线程私有数组,然后在最后合并它们:
推荐阅读
- grafana - Cloudwatch 指标中的元数据(替代维度?)
- ubuntu - Nuxt 与 Apache2 返回 502 代理错误:从远程服务器读取错误
- vector - 比较两个二维特征向量,找出它们的相似度
- c++ - 命名空间的类的朋友,未在命名空间中声明和定义
- clang - LLVM IR 代码中是否需要对齐指令?
- php - 将 CSV 导入 SQL 表适用于 XAMPP,但不适用于在线服务器
- c++ - 初始化 std::unordered_map 类型的 std::shared_ptr 时编译错误
- asp.net-mvc - 我可以在 VS2019 的 BeforePublish 事件中更改 webconfig 文件中的 connectionString 文本吗?
- python-3.x - 'pygame.Surface' 对象没有属性 'draw'
- bash - 如何拆分 ls -l 的输出以正确的格式显示