Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenMP - Variable declarations in for loops

I'm trying to adapt a normal code to a parallel one. When I make a for loop parallel, which has some variables declared inside of it, are those variables private or shared?

Should I define each of them as private when I define the pragma?


By the way, one last question. I can use for-pragma with an initial parameter of an iterator too right? like for(iter=xlist.begin() ; ... )

I use latest version of codeblocks and mingw.

like image 539
serkank Avatar asked Dec 13 '22 12:12

serkank


1 Answers

Anything declared inside a parallel region (whether it's a loop or not) is private, with exceptions as listed below in @ejd 's comment. You can't list it as private on the #pragma line as the variable doesn't exist yet.

So for instance in the below, even with default(none) we don't need to specify the sharing of tid even if you could; it's inside the parallel section, so it is private to each thread. (Note too that you don't really need to specify i as private, as the loop index of an omp for is necessarily private.)

$ more foo.c
#include <stdio.h>
#include <omp.h>

int main(int argc, char *argv[]) {
    int i;

    #pragma omp parallel for default(none) private(i)
    for(i=0;i<10;i++){
        int tid = omp_get_thread_num();
        printf("Thread %d gets iteration %d\n", tid, i);
    }

    return 0;
}
gpc-f103n084-$ !g
gcc -o foo foo.c -fopenmp 
$ ./foo
Thread 1 gets iteration 2
Thread 1 gets iteration 3
Thread 3 gets iteration 6
Thread 3 gets iteration 7
Thread 0 gets iteration 0
Thread 0 gets iteration 1
Thread 4 gets iteration 8
Thread 4 gets iteration 9
Thread 2 gets iteration 4
Thread 2 gets iteration 5
like image 136
Jonathan Dursi Avatar answered Dec 15 '22 02:12

Jonathan Dursi