可通过设置 OMP_NESTED 环境变量来启用或禁用嵌套并行操作。缺省情况下,禁用嵌套并行操作。
以下示例中的嵌套并行构造具有三个级别。
示例 3-1 嵌套并行操作示例#include <omp.h>
#include <stdio.h>
void report_num_threads(int level)
{
#pragma omp single
{
printf("Level %d: number of threads in the team = %d\n",
level, omp_get_num_threads());
}
}
int main()
{
omp_set_dynamic(0);
#pragma omp parallel num_threads(2)
{
report_num_threads(1);
#pragma omp parallel num_threads(2)
{
report_num_threads(2);
#pragma omp parallel num_threads(2)
{
report_num_threads(3);
}
}
}
return(0);
}
启用嵌套并行操作时,编译和运行此程序会产生以下(经过排序的)输出:
% setenv OMP_NESTED TRUE % a.out | sort Level 1: number of threads in the team = 2 Level 2: number of threads in the team = 2 Level 2: number of threads in the team = 2 Level 3: number of threads in the team = 2 Level 3: number of threads in the team = 2 Level 3: number of threads in the team = 2 Level 3: number of threads in the team = 2
在禁用嵌套并行操作的情况下运行程序会生成以下输出:
% setenv OMP_NESTED FALSE % a.out | sort Level 1: number of threads in the team = 2 Level 2: number of threads in the team = 1 Level 2: number of threads in the team = 1 Level 3: number of threads in the team = 1 Level 3: number of threads in the team = 1