开发者

OpenMP - Variable declarations in for loops

开发者 https://www.devze.com 2023-03-10 22:24 出处:网络
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?

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 priv开发者_如何学编程ate 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.


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


If you need them only within the loop block and you want to parallelize the loop, leave them inside the loop block. If you declare them outside of the parallel construct and declare them as private, each thread will have its own copy. So it doesn't matter.

0

精彩评论

暂无评论...
验证码 换一张
取 消