c++ - OpenMP,for 循环内部部分

标签 c++ c openmp

我想运行以下代码(如下)。我想生成两个独立的线程,每个线程都会运行一个并行的 for 循环。不幸的是,我收到一个错误。显然,并行 for 无法在 section 内生成。怎么解决?

#include <omp.h>
#include "stdio.h"

int main()
{

omp_set_num_threads(10);

#pragma omp parallel    
#pragma omp sections
  {
#pragma omp section
#pragma omp for
    for(int i=0; i<5; i++) {
        printf("x %d\n", i);
    }

#pragma omp section
#pragma omp for
    for(int i=0; i<5; i++) {
        printf(". %d\n", i);
    }
  } // end parallel and end sections
}

错误:

main.cpp: In function ‘int main()’:
main.cpp:14:9: warning: work-sharing region may not be closely nested inside of work-sharing, critical, ordered, master or explicit task region [enabled by default]
main.cpp:20:9: warning: work-sharing region may not be closely nested inside of work-sharing, critical, ordered, master or explicit task region [enabled by default]

最佳答案

这里你必须使用嵌套并行性。 sections 中的 omp for 的问题在于,作用域内的所有线程都必须参与 omp for,而且它们显然不参与t——它们被分成几个部分。所以你必须引入函数,并在函数内进行嵌套并行。

#include <stdio.h>
#include <omp.h>

void doTask1(const int gtid) {
    omp_set_num_threads(5);
#pragma omp parallel 
    {
        int tid = omp_get_thread_num();
        #pragma omp for
        for(int i=0; i<5; i++) {
            printf("x %d %d %d\n", i, tid, gtid);
        }
    }
}

void doTask2(const int gtid) {
    omp_set_num_threads(5);
#pragma omp parallel 
    {
        int tid = omp_get_thread_num();
        #pragma omp for
        for(int i=0; i<5; i++) {
            printf(". %d %d %d\n", i, tid, gtid);
        }
    }
}


int main()
{
    omp_set_num_threads(2);
    omp_set_nested(1);

#pragma omp parallel    
    {
        int gtid = omp_get_thread_num();
#pragma omp sections
        {
#pragma omp section
            doTask1(gtid);

#pragma omp section
            doTask2(gtid);
        } // end parallel and end sections
    }
}

关于c++ - OpenMP,for 循环内部部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45415427/

相关文章:

c++ - 将加法运算符重载为非成员函数是否更好?

c - 在 C 中定义全局常量

c++ - 如何在 OS X 中包含 omp.h?

c++ - 用于应用程序本地部署的 MSVC 2015 通用 CRT

c++ - Lexical_cast 抛出异常

c - 如何将链表从一个文件传递到同一项目中的另一个文件?

c - c中没有结构的反向二进制文件

c++ - 通过 Openmp 任务访问实例变量(隐式 firstprivate)时出现段错误

c++ - 在 OpenMP for 循环中更新 HashMap

c++ - 为什么具有继承构造函数的类也会获得合成的默认构造函数?