Frage

I have a problem with OpenMp. I need to compute Pi with OpenMP and Monte Carlo. I write simple program and i am reading number of threads from command line. Now it is working not stable sometimes 1 thread is faster than 16. Have anyine idea what am i doing wrong?

int main(int argc, char*argv[])
{
int niter, watki;
watki = strtol(argv[1], NULL, 0);
niter = strtol(argv[2], NULL, 0);
intcount=0                                                                          
int i;
double x, y, z;
double pi;
omp_set_dynamic(0);  
unsigned int myseed = omp_get_thread_num();
double start = omp_get_wtime();
omp_set_num_threads(watki);
#pragma omp parallel for private(i,x,y,z) reduction(+:count)
  for ( i=0; i<niter; i++) {                                                                              
    x = (double)rand_r(&myseed)/RAND_MAX;                                                                          
    y = (double)rand_r(&myseed)/RAND_MAX;                                                                          
    z = x*x+y*y;                                                                                          
    if (z<=1) count++;                                                                                      
  }                                                                                                      
pi=(double)count/           niter*4;                                                                                   
printf("# of trials= %d, threads %d , estimate of pi is %g \n",niter, watki,pi); 
double end = omp_get_wtime();
printf("%f \n", (end - start));
}

I compile it with gcc -fopenmp pi.c -o pi And run it with ./pi 1 10000 Thanks in advance

War es hilfreich?

Lösung

You're calling omp_get_thread_num outside of the parallel region, which will always return 0.

Then all your rand_r calls will access the same shared seed, which is probably the source of your problem. You should declar myseed within the loop to make it private to each thread, and to get the correct value from omp_get_thread_num

#pragma omp parallel for private(i,x,y,z) reduction(+:count)
for ( i=0; i<niter; i++) {
  int myseed = omp_get_thread_num();
  x = (double)rand_r(&myseed)/RAND_MAX;               
  y = (double)rand_r(&myseed)/RAND_MAX;               
  z = x*x+y*y;      
  if (z<=1) count++;  
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top