首页 > 解决方案 > 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

标签: c++openmp

解决方案


选项 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:如果与同步开销相比迭代太便宜,您可以让每个向量填充一个线程私有数组,然后在最后合并它们:

这里这里有一个很好的副本。


推荐阅读