#include <omp.h>
#include <stdio.h>
int main()
{
int n = 4;
int i, j;
#pragma omp parallel num_threads(2) private(i)
for (i = 0;i < n;i++)
{
int outer_tid = omp_get_thread_num();
printf("outside thread id is %d, i = %d.\n", outer_tid,i);
if (i%2 == 0)
#pragma omp for
for (j = 0;j < n;j += 2)
{
printf("even, outside thread is %d, inner thread id is %d, i = %d, j = %d.\n", outer_tid , omp_get_thread_num(), i, j);
}
else
#pragma omp for
for (j = 1;j < n;j += 2)
{
printf("odd, outside thread is %d, inner thread id is %d, i = %d, j = %d.\n", outer_tid , omp_get_thread_num(), i, j);
}
}
return 0;
}
输出
outside thread id is 0, i = 0.
even, outside thread is 0, inner thread id is 0, i = 0, j = 0.
outside thread id is 1, i = 0.
even, outside thread is 1, inner thread id is 1, i = 0, j = 2.
outside thread id is 0, i = 1.
odd, outside thread is 0, inner thread id is 0, i = 1, j = 1.
outside thread id is 1, i = 1.
odd, outside thread is 1, inner thread id is 1, i = 1, j = 3.
outside thread id is 0, i = 2.
even, outside thread is 0, inner thread id is 0, i = 2, j = 0.
outside thread id is 1, i = 2.
even, outside thread is 1, inner thread id is 1, i = 2, j = 2.
outside thread id is 0, i = 3.
odd, outside thread is 0, inner thread id is 0, i = 3, j = 1.
outside thread id is 1, i = 3.
odd, outside thread is 1, inner thread id is 1, i = 3, j = 3.
显然,
for (i = 0;i < n;i++)
{
int outer_tid = omp_get_thread_num();
printf("outside thread id is %d, i = %d.\n", outer_tid,i);
已由线程0和1执行。但是嵌套的omp for directive没有重复执行。我想为线程0,当i = 0时,它会与嵌套for和线程1并行,当i = 0时,所以有重复。但输出证明我错了。 openmp处理这种情况的策略是什么?