c++ - 使用 openmp 并行化 for 循环并替换 push_back

标签 c++ for-loop parallel-processing openmp

我想并行化以下代码,但我是 openmp 和创建并行代码的新手。

std::vector<DMatch> good_matches;
for (int i = 0; i < descriptors_A.rows; i++) {
   if (matches_RM[i].distance < 3 * min_dist) {
      good_matches.push_back(matches_RM[i]);
   }
}

我试过了

std::vector<DMatch> good_matches;
#pragma omp parallel for
for (int i = 0; i < descriptors_A.rows; i++) {
   if (matches_RM[i].distance < 3 * min_dist) {
      good_matches[i] = matches_RM[i];
   }
}

std::vector<DMatch> good_matches;
cv::DMatch temp;
#pragma omp parallel for
for (int i = 0; i < descriptors_A.rows; i++) {
   if (matches_RM[i].distance < 3 * min_dist) {
      temp = matches_RM[i];
      good_matches[i] = temp;
      // AND ALSO good_matches.push_back(temp);
   }

我也试过

#omp parallel critical 
good_matches.push_back(matches_RM[i]);

此子句有效但不会加快任何速度。可能无法加速此 for 循环,但如果可以的话,那就太好了。我也想加快速度

std::vector<Point2f> obj, scene;
for (int i = 0; i < good_matches.size(); i++) {
   obj.push_back(keypoints_A[good_matches[i].queryIdx].pt);
   scene.push_back(keypoints_B[good_matches[i].trainIdx].pt);
}

如果这个问题得到了回答,我们深表歉意,非常感谢任何可以提供帮助的人。

最佳答案

我在这里展示了如何做到这一点 c-openmp-parallel-for-loop-alternatives-to-stdvector

制作 std::vector 的私有(private)版本并在关键部分填充共享 std::vector,如下所示:

std::vector<DMatch> good_matches;
#pragma omp parallel
{
    std::vector<DMatch> good_matches_private;
    #pragma omp for nowait
    for (int i = 0; i < descriptors_A.rows; i++) {
       if (matches_RM[i].distance < 3 * min_dist) {
          good_matches_private.push_back(matches_RM[i]);
       }
    }
    #pragma omp critical
    good_matches.insert(good_matches.end(), good_matches_private.begin(), good_matches_private.end());
}

关于c++ - 使用 openmp 并行化 for 循环并替换 push_back,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24765180/

相关文章:

javascript - 初学者 JavaScript; for 循环,对象数组显示为未定义

C++ - 如何从头到尾遍历列表?

c++ - 在 C++ 中哪个更快 : i<=N or i<N+1

c# - 无论如何并行产量 c#

c++ - 如何编写代码在 C++ 中进行条件模板实例化

c++ - 容器的 begin() 和 end() 的不同实现

c++ - 模板的合格和不合格名称查找的不同行为

c++ - std::_throw_out_of_range 不知从何而来

multithreading - 使用 -N(并行)标志运行时 GHC 在做什么?

c - 使用 omp parallel for 但不是顺序时出现段错误