parallel for loop counter

General OpenMP discussion

parallel for loop counter

Postby ianyappy » Tue Oct 16, 2012 8:06 am

Hi, newbie here. Was wondering if either of these parallel for examples are incorrect,

Code: Select all
#include <omp.h>
#include <iostream>
using namespace std;
int main() {
    int i;
    const int ARR_SIZE = 5;
    int tmpArr1[ARR_SIZE];
    int tmpArr2[ARR_SIZE];
   
    #pragma omp parallel for private(i)
    for(i = 0; i < ARR_SIZE; i++)
        tmpArr1[i] = i;

    #pragma omp parallel for
    for(i = 0; i < ARR_SIZE; i++)
        tmpArr2[i] = i;

    cout << "tmpArr1" << endl;
    for(i = 0; i < ARR_SIZE; i++)
        cout << tmpArr1[i] << endl;
    cout << "tmpArr2" << endl;
    for(i = 0; i < ARR_SIZE; i++)
        cout << tmpArr2[i] << endl;

    return 0;
}


i.e. do I have to declare the counter private, or does OpenMP somehow recognize what to do? I believe there are also numerous examples where parallel for is done with the loop counter declared in the for parentheses. I have run the code and the output looks correct.
ianyappy
 
Posts: 2
Joined: Mon Oct 15, 2012 8:15 am

Re: parallel for loop counter

Postby MarkB » Wed Oct 17, 2012 9:33 am

The loop iterator for the parallel loop is automatically private. It does no harm to declare it private explicitly, though, so both your examples are correct.

You do, however, need to take care to make loop iterators of enclosed sequential loops private:

Code: Select all
 
#pragma omp parallel for   // Bug! j must appear in a private clause here.
    for(i = 0; i < ARR_SIZE; i++)
         for(j = 0; j < ARR_SIZE; j++)
                 Arr1[i][j] = i+j;


This bug can often go unnoticed as an optimising compiler may never actually store the value of j in memory.

As you say, another option is to declare the iterators in the scope of the loop:

Code: Select all
 
#pragma omp parallel for   
    for(int i = 0; i < ARR_SIZE; i++)
         for(int j = 0; j < ARR_SIZE; j++)
                 Arr1[i][j] = i+j;


In this case the iterators are not in scope at the parallel for construct, so cannot appear in a private clause.

Hope that helps,
Mark.
MarkB
 
Posts: 428
Joined: Thu Jan 08, 2009 10:12 am

Re: parallel for loop counter

Postby ianyappy » Fri Oct 19, 2012 8:00 am

Ok, got it, thanks.
ianyappy
 
Posts: 2
Joined: Mon Oct 15, 2012 8:15 am


Return to Using OpenMP

Who is online

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