C -PI在OpenMP中不取决于线程



我对OpenMP有问题。我需要用OpenMP和Monte Carlo计算PI。我编写简单的程序,并且正在读取命令行中的线程数。现在,它的工作不稳定,有时1个线程比16更快。有任何想法我在做什么错?

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));
}

我用gcc -fopenmp pi.c -o pi编译它并用./pi 1 10000运行预先感谢

您正在并行区域外调用omp_get_thread_num,它将始终返回0。

然后,您的所有rand_r调用都将访问相同的共享种子,这可能是您问题的来源。您应该在循环中声明myseed,以使其私密地到每个线程,并从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++;  
}

最新更新