c++ - 在调用第二个函数之前等待整个 omp block 完成

标签 c++ openmp

我没有在 C++ 中使用 openmp 的经验,我想了解如何正确解决我的问题。我有 30 个文件需要由相同的函数独立处理。每次激活该功能时,都会生成一个新的输出文件(out01.txt 到 out30.txt)保存结果。我的机器上有 12 个处理器,我想用 10 个来解决这个问题。

我需要更改我的代码以等待处理完所有 30 个文件以执行 C++ 中的其他例程。此时,我无法强制我的代码等待所有 omp 作用域被执行,然后移动第二个函数。

请在下面找到我的代码草稿。

   int W = 10; 
   int i = 1;
   ostringstream fileName;
   int th_id, nthreads;

        omp_set_num_threads(W);
        #pragma omp parallel shared (nFiles) private(i,fileName,th_id)
        {
             #pragma omp for schedule(static)
            for ( i = 1; i <= nFiles; i++)
            {
                th_id = omp_get_thread_num();
                 cout << "Th_id: " << th_id << endl;

            // CALCULATION IS PERFORMED HERE FOR EACH FILE

            }
        }

            // THIS is the point where the program should wait for the whole block to be finished
            // Calling the second function ...

最佳答案

“omp for”和“omp parallel”编译指示在其范围的末尾都有一个隐式屏障。因此,在并行部分结束之前,并行部分之后的代码无法执行。所以您的代码应该可以完美运行。

如果仍然存在问题,那不是因为您的代码没有在并行区域的末尾等待。

请向我们提供有关执行此代码期间发生的情况的更多详细信息。这样我们或许能够找到您问题的真正原因。

关于c++ - 在调用第二个函数之前等待整个 omp block 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52956974/

相关文章:

matrix - Fortran中多线程矩阵的转置

c++ - "omp single"和 "omp task"如何提供并行性?

c++ - boost signals2 - 通过插槽断开连接时出错

c++ - 当函数未在默认返回路径上显式返回值时强制出错?

C++ 递归 mpl::equal 问题?

c++ - openmp g++错误: collapsed loops not perfectly nested

c - OpenMP : Parallel QuickSort

c++ - 了解基本的动态分配示例

c++ - 如何在不更改 C++ 中的原始链表的情况下反转链表

c++ - 将 OpenMP 应用于 C++ 中的特定嵌套循环