I have newly started learning openmp programming but got stuck in a piece of code which tries to parallelize the program for calculation of pi. I'm unable to undertand what this line do in the program and meaning of the followed comment.
if (id == 0) nthreads = nthrds; //Only one thread should copy the number of threads to the global value to make sure multiple threads writing to the same address don’t conflict.
The entire code is:
#include<omp.h>
#include<stdio.h>
#define NUM_THREADS 2
static long num_steps = 100000;
double step;
int main ()
{
int i, nthreads;
double pi, sum[NUM_THREADS];
step = 1.0/(double) num_steps;
omp_set_num_threads(NUM_THREADS);
double time1 = omp_get_wtime();
#pragma omp parallel
{
int i, id,nthrds;
double x;
id = omp_get_thread_num();
nthrds = omp_get_num_threads();
if (id == 0) nthreads = nthrds; //Only one thread should copy
the number of threads to the global value to make sure multiple
threads writing to the same address don’t conflict.
for (i=id, sum[id]=0.0;i< num_steps; i=i+nthrds){
x = (i+0.5)*step;
sum[id] += 4.0/(1.0+x*x);
}
}
double time2 = omp_get_wtime();
for(i=0, pi=0.0;i<nthreads;i++)pi += sum[i] * step;
printf("%lf\n",pi);
printf("%lf\n",(time2-time1));
}
I tried to run without the if statement but it gave the value of pi 0 but ran correctly otherwise (gave 3.141593). When I tried to assign nthreads equal to total number of threads (ie 2) outside globally it still gave correct value of pi. Can anybody explain me the how there is difference in the ouput?
Thank you!!