Using OpenMP to calculate the value of PI

我的梦境 提交于 2019-12-12 12:04:25

问题


I'm trying to learn how to use OpenMP by parallelizing a monte carlo code that calculates the value of PI with a given number of iterations. The meat of the code is this:

  int chunk = CHUNKSIZE;                                                                                      

    count=0;                                                                                                  
#pragma omp parallel shared(chunk,count) private(i)                                                           
  {                                                                                                           


#pragma omp for schedule(dynamic,chunk)                                                                       
      for ( i=0; i<niter; i++) {                                                                              
        x = (double)rand()/RAND_MAX;                                                                          
        y = (double)rand()/RAND_MAX;                                                                          
        z = x*x+y*y;                                                                                          
        if (z<=1) count++;                                                                                    
      }                                                                                                       
  }                                                                                                           

  pi=(double)count/niter*4;                                                                                   
  printf("# of trials= %d , estimate of pi is %g \n",niter,pi);  

Though this is not yielding the proper value for pi given 10,000 iterations. If all the OpenMP stuff is taken out, it works fine. I should mention that I used the monte carlo code from here: http://www.dartmouth.edu/~rc/classes/soft_dev/C_simple_ex.html

I'm just using it to try to learn OpenMP. Any ideas why it's converging on 1.4ish? Can I not increment a variable with multiple threads? I'm guessing the problem is with the variable count.

Thanks!


回答1:


Okay, I found the answer. I needed to use the REDUCTION clause. So all I had to modify was:

#pragma omp parallel shared(chunk,count) private(i)

to:

#pragma omp parallel shared(chunk) private(i,x,y,z) reduction(+:count)

Now it's converging at 3.14...yay



来源:https://stackoverflow.com/questions/6192807/using-openmp-to-calculate-the-value-of-pi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!