问题
I have a question about OpenMP. Does it make any difference whether I declare i
in the outer loop as private or shared?
int i,j;
#pragma omp parallel for private(j)
for (i=0; i<n; i++) {
for(j=0; j<n; j++) {
//do something
}
}
回答1:
i
should be defined as private in your code. As each thread will run a proportion of the i
loop, each thread should keep a private i
so that the loop body knows which iteration he is in.
However a better way is to define variables when you use them, so that you don't need to specify their properties in most cases. In the following example, every variable (i and j) defined in the parallel for loop is private by default.
#pragma omp parallel for
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
//do something
}
}
回答2:
Technically it does not make a difference, because the standard explicitly states the loop variable in the canonical loop form is always implicitly private.
If this variable would otherwise be shared, it is implicitly made private in the loop construct.
[2.6 in OpenMP API 4.5]
I would advise against declaring it shared, it would be very confusing to to anyone trying to read the program. You might argue that you could have the variable being shared outside of the loop and private inside, but I can't think of a case where this would make sense.
I'd hoped the compiler would give you a warning in that case, but at least GCC does not.
来源:https://stackoverflow.com/questions/37845291/openmp-outer-loop-private-or-shared