variable initialization

General OpenMP discussion

variable initialization

Postby ppaul127 » Wed Nov 28, 2007 3:46 pm

Hi
Hope this is the right place to post questions from newbies.
I was wondering if there is an elegant way to initialize private variables when parallelizing a loop.
To illustrate the question with a simple example :

This loop which fills the value 10, 9, 8, etc. in an array of 10 elements, and I want to use the -- operator in the loop to do so.

Code: Select all
int a[10];
int i;
int val=10;
for (i=0;  i<10;  ++i) {
   a[i] = val;
   val--;
}


I was thinking of using openmp this way :

Code: Select all
#pragma omp parallel for firstprivate(val) private(i) schedule(static)
for (i=0;  i<10;  ++i) {
  a[i] = val;
  val--;
}


but of course val is initialized to 10 for each thread and this not going to work.
I thought of initialising val in the for statement
Code: Select all
for(i=0,val=10-i; ... )
but this is not supported.

I know we could rewrite the code easily to make it work (a[i]=val-i) , but this is a general question on private variables initialization.

Is there a simple / recommanded way to initialize variables used by each thread ?

Thanks for any advice
ppaul127
 
Posts: 2
Joined: Wed Nov 28, 2007 3:21 pm

Re: variable initialization

Postby lfm » Fri Nov 30, 2007 11:38 am

If you want a private variable to be a function of the thread number, you can use the omp_get_thread_num() function. I also tend to prefer using the C language scoping rules rather than the private clause, though that is more of a personal preference. So something like:
Code: Select all
#include <omp.h>
...
#pragma omp parallel
{
   int nthreads = omp_get_num_threads();
   int mythread = omp_get_thread_num();
   val = (10 / nthreads) * mythread + 1;
#pragma omp for
   for (int i = 0; i < 10; ++i)
      a[i] = val--;
}


Note that this works only if nthreads is 5 or 2. You can also use threadprivate data, which is global and persistent in some cases.

None of these are really great programming style. If you can avoid thinking about explicit thread numbers in your code and avoid global static data then you usually end up with more flexible and maintainable programs.

-- Larry
lfm
 
Posts: 135
Joined: Sun Oct 21, 2007 4:58 pm
Location: OpenMP ARB

Re: variable initialization

Postby ppaul127 » Sun Dec 02, 2007 6:54 am

Thanks for the answer Larry.
ppaul127
 
Posts: 2
Joined: Wed Nov 28, 2007 3:21 pm


Return to Using OpenMP

Who is online

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