When I enter i = 1 it outputs:
c[0] = 7
c[0] = 7
c[0] = 7
c[0] = 7
c[0] = 7
but when i enter i = 0 it outputs:
c[1] = 9
c[2] = 11
c[3] = 13
c[4] = 15
c[0] = 7
shouldn't the output of i = 0 be the output of i = 1 and vice versa?
#include<omp.h>
#include<stdio.h>
int main(){
int a[5] = {1, 2, 3, 4, 5} ;
int b[5] = {6, 7, 8, 9, 10} ;
int c[5];
int tid;
int i;
scanf("%d", &i);
#pragma omp parallel if(i)
{
#pragma omp parallel num_threads(5)
{
tid = omp_get_thread_num();
c[tid] = a[tid] b[tid];
printf("c[%d] = %d\n", tid, c[tid]);
}
}
}```
CodePudding user response:
The behaviour you see is correct (assuming that the variable tid
has been declared private
as otherwise you have a race condition here).
Indeed, the first #pragama omp parallel if(i)
will create a parallel region with an implementation defined number of threads if and only if i
isn't 0
.
But then, if the parallel region has been created, then the following #pragma omp parallel num_threads(5)
will be ignored as by default, nested parallelism is disabled.
And if i
was 0
and the first parallel region wasn't created (no more nested parallelism here), then the second one will indeed be created and 5 threads will be spawned.
In summary, i
non null prevents the inner parallel region to be created, while i
null allows it.