Why do people declare iterated values ​​before the loop for openmp?

So, from what I understand, any of them is true in all versions of openmp:

//int i declared in loop, explicitly private #pragma omp parallel for for (int i = 0; i < NUMEL; i++) { foo(i); } //int i declared outsize loop, but is the iterated value, implicitly private int i; #pragma omp parallel for for (i = 0; i < NUMEL; i++) { foo(i); } 

However, I often see the second than the first. Why is this?

+2
c ++ openmp
Apr 01 '14 at 15:24
source share
3 answers

Because not everyone writes in C ++ or targets a C99-compatible C compiler. Some people prefer to stick to the old C requirement for variables declared at the beginning of the block so that the code is more compatible with old (pre-C99) C compilers.

+4
Apr 01 '14 at 15:31
source share

Declaring loop iterators outside the loop is error prone and usually not necessary. Perhaps the biggest share of SO questions about OpenMP is problems due to internal loops and declaring iterators outside of loops.

 int i,j; #pragma omp parallel for for(i=0; i<n; i++) { //OpenMP makes the parallel index private by default for( j=0; j<n; j++) { //error j should be private but is shared by default 

If the initial declarations of the loop were used, this type of error would not be

 #pragma omp parallel for for(int i=0; i<n; i++) { //i is private for(int j=0; j<n; j++) {// j is private now 

The GNU89 C dialog, which GCC and ICC by default, unfortunately, do not allow the initial declarations of the loop (even if it allows mixed declarations), so the C99 (e.g. GNU99) dialect or C ++ is needed for the initial declarations of the loop.

However, it is sometimes useful to declare an iterator outside the loop when the last iterator is desired. In this case, use lastprivate . For example, if I only wanted to iterate over several elements from four elements, and then find out how many finite elements were used, I could do:

 #include <stdio.h> int main() { int i,j; int n,m; n = 10; m = 25; #pragma omp parallel for lastprivate(i,j) for(i=0; i<(n & -4); i++) { for(j=0; j<(m & -4); j++) { } } printf("%d %d\n",i, j); //output 8, 24 } 
+2
Apr 01 '14 at 19:47
source share

One programmer told me that he prefers the second version, because you can see the i value in the debugger after the loop exits, which is useful for loops with complex conditions or breaks . But these loops will not be well parallelized, so I would be surprised if this is the reason for the OpenMP examples.

0
Apr 01 '14 at 15:38
source share



All Articles