- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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?
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
AFAIK, #pragma omp parallel for private(indigo, sausage)
but I'm a newbie, so dont trust me.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page