Nested Loop

General OpenMP discussion

Nested Loop

Postby simone.at » Mon Jul 14, 2014 9:29 am

Hi all,

I have the following nested for-loops.

------------------------------------------------------------------------------
int i,j;

#pragma omp parallel for schedule(static)
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
data[i] += data2[j*N + i];
}
}
------------------------------------------------------------------------------

In this case only the outer loop will be parallelized, so each thread will execute the entire inner loop.
The index "j" will be shared by default? If yes, there will be a data race on it, am I wrong?

Thanks.
Best,
Simone
simone.at
 
Posts: 2
Joined: Thu Feb 06, 2014 5:37 pm

Re: Nested Loop

Postby ftinetti » Tue Jul 15, 2014 3:44 am

Hi Simone,

I never remember defaults... and partially to avoid looking for it in the Spec. and partially for documentation purposes (and let compilers check) I usually write explicitly what I need. In this case:

Code: Select all
int i,j;
...
#pragma omp parallel for private(i, j) shared(N, M, data, data2) schedule(static)
for (i = 0; i < N; i++) {
   for (j = 0; j < M; j++) {
     data[i] += data2[j*N + i];
   }
}


The index "j" will be shared by default? If yes, there will be a data race on it, am I wrong?

As I wrote above, I don't remember defaults (check the Spec., please), but in case "j" is shared there will be a data race on it.


HTH,

Fernando.
ftinetti
 
Posts: 582
Joined: Wed Feb 10, 2010 2:44 pm

Re: Nested Loop

Postby MarkB » Tue Jul 15, 2014 4:10 am

j is indeed shared by default in this case, so there is a race.

This bug can often go unnoticed because, with sufficient optimisation, the compiler will never actually store j in memory. The code then behaves as if j were private, but you should certainly not rely on this!

I always recommend using default(none) in addition to explicitly data-scoping all variables to help catch this type of bug. Using the more modern style of declaring loop indices in the scope of the loop also helps.
MarkB
 
Posts: 450
Joined: Thu Jan 08, 2009 10:12 am
Location: EPCC, University of Edinburgh


Return to Using OpenMP

Who is online

Users browsing this forum: Google [Bot] and 14 guests