我在使用openMP计算Pi这个简单的程序时遇到了麻烦。它适用于1,2或4个线程,但它挂起3个线程,我不知道为什么。以下是使用-fopenmp
在GCC中编译的完整代码#include<stdio.h>
#include<math.h>
#include<omp.h>
#include<time.h>
#define NUM_THREADS 3
void main(){
long num_steps = 100000;
double c1,c2;
int i,nthreads,id;
double p=0.,sum[NUM_THREADS-1],pi=0.;
double x,local_sum;
double step = 1.0/((double)num_steps);
c1=omp_get_wtime();
#pragma omp parallel num_threads(NUM_THREADS) shared(sum) private(i,id,local_sum,x)
{
id = omp_get_thread_num();
local_sum = 0.;
for(i=id;i<=num_steps;i=i+NUM_THREADS)
{
x=(i+0.5)*step;
local_sum=local_sum+4.0/(1.0+x*x);
}
sum[id] = local_sum;
}
for(i=0;i<=NUM_THREADS-1;i++) {pi += step*sum[i]; printf("sum[%d] = %lf\n",i,sum[i]);}
printf("pi = %lf\n",pi);
c2=omp_get_wtime();
printf("tempo = %f s\n",(c2-c1));
}