reduction(+:x), where x is a vector

General OpenMP discussion

reduction(+:x), where x is a vector

Postby rajeshmondal18 » Tue Nov 26, 2013 11:48 am

I am trying to parallelise a program, which is as simple as like this
//##############################################################################
#include<stdio.h>
#include<omp.h>
main()
{
long i,x[4];
double t;
x[0]=0;x[1]=0;x[2]=0;x[3]=0;

t= omp_get_wtime();
for(i=0;i<10000000;i++)
x[i%4]++;
printf("%d\t%d\t%d\t%d\t time=%e\n",x[0],x[1],x[2],x[3],omp_get_wtime()-t);
} //########################################################################################

I have tried several methods to parallelise that. I got right answer (i.e. 2500000 2500000 2500000 2500000), but time for parallelise version is more than that serial one. How can I use reduction(+:x), where x is a vector.
rajeshmondal18
 
Posts: 2
Joined: Tue Nov 26, 2013 11:06 am

Re: reduction(+:x), where x is a vector

Postby MarkB » Tue Nov 26, 2013 2:39 pm

You cannot specify a C array in an OpenMP reduction clause, so you need to make a private copy of x explicitly and then reduce these into the final result using some appropriate synchronisation, for example:

Code: Select all
long my_x[4];

#pragma omp parallel private(my_x) shared(x)
{

for(int j=0;j<4;j++) {
   my_x[j] = 0;
}

#pragma omp for
for(i=0;i<10000000;i++){
  my_x[i%4]++;
}

#pragma omp critical
{
  for(int j=0;j<4;j++) {
     x[j] += my_x[j];
  }
}

}
MarkB
 
Posts: 432
Joined: Thu Jan 08, 2009 10:12 am

Re: reduction(+:x), where x is a vector

Postby rajeshmondal18 » Tue Nov 26, 2013 9:32 pm

Thank you MarkB.
rajeshmondal18
 
Posts: 2
Joined: Tue Nov 26, 2013 11:06 am


Return to Using OpenMP

Who is online

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