Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.

Sharing variables in OpenMP

hellary
Beginner
329 Views
This should be an easy one for anyone that's used OpenMP before!

How do I share a variable in a parallel loop.

I.e.:

#pragma omp parallel for

for(i=0;i {
for(j=0;j {
indigo=array1*array2;
sausage=sqrt(indigo);
array3=sausage;
}
}


The problem is that sausage and indigo need to be independent for each thread. Now I guess I could use the thread number and the total number of threads to somehow create an array for each indigo and sausage but I'm sure there's something built into openmp where you can just say "give each thread their own version of indigo and sausage".

Any ideas?
0 Kudos
4 Replies
Intel_C_Intel
Employee
329 Views

AFAIK, #pragma omp parallel for private(indigo, sausage)

but I'm a newbie, so dont trust me.

0 Kudos
hellary
Beginner
329 Views
I just worked that out too, thanks anyway though!! Seems to be working just fine this way. :)
0 Kudos
jimdempseyatthecove
Honored Contributor III
329 Views

Not only do sausage and indigo need to be thread private but also j needs to be thread private.

An alternate way from using the private or shared on the pragman is to declare the private variables inside the scope of the parallel loop.

#pragma omp parallel for 
for(i=0;i { // i private by default
int j; // private j
for(j=0;j {
// private indego
float indigo=array1*array2;
// private sausage
float sausage=sqrt(indigo);
array3=sausage;
}
}

Note, variables j, indigo and sausage are declared inside the scope of the parallel loop and therefore will be stack local to each thread.

A cautionary note.

Often a programmer may code a loop with an early exit and that the code following the major loop will examine the index variable to see if it expired early. This will not work in parallel programming. Instead you should use a shared variable to indicate an abnormal exit.

volatile bool abEnd = FALSE;
#pragma omp parallel for
for(i=0;i {
int j; // seperate j per thread
for(j=0;j {
float indigo=array1*array2;
float sausage=sqrt(indigo);
array3=sausage;
// do not remove following if expression
// i.e. do not use "abEnd = fpInvalid(sausage);"
// as other thread may clear the abEnd
if(fpInvalid(sausage)) abEnd = TRUE;
// do test outside statement scope of above if
// because other thread may have abEnded.
if(abEnd) break;
}
if(abEnd) break;
}
if(abEnd) doAbEndProcess();

Where fpInvalid tests for NaN, overflow, and or other non-sensical results.

Jim Dempsey

0 Kudos
levicki
Valued Contributor I
329 Views

Jim, when you write code blocks here be sure to replace < with & lt ; and > with & gt ; (just remove spaces around lt and gt) or it will get mangled beyond recognition.

0 Kudos
Reply