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++) {
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 }
Z boson Apr 01 '14 at 19:47 2014-04-01 19:47
source share