Search code examples
cmultithreadingparallel-processingopenmppragma

Why does this code which calculates Pi value using openmp gives a slightly different answer(the last few floating points) each time?


This is my solution using openmp which i used to parallelize the code which calculates Pi. The floating point value of Pi changes each time this is executed. Could someone explain why?

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>

#define THREAD_NUM 20

static long num_steps = 100000;
double step;

int main(){

    int i;
    double x; 
    double pi;
    double sum = 0.0;
    double t1 = 0.0;
    double t2 = 0.0;

    step = 1.0/(double) num_steps;
    omp_set_num_threads(THREAD_NUM);
    t1 = omp_get_wtime();

    #pragma omp parallel
    {
        double p_sum = 0.0;

        #pragma omp for
        for(i=0; i<num_steps; i++){
    
            x = (i+0.5)*step;
            p_sum = p_sum + 4.0/(1.0+x*x);
        }

        #pragma omp atomic
        sum += p_sum;
    }

    t2 = omp_get_wtime();
    pi = step*sum;

    printf("value of pi = %lf\n", pi);
    printf("time = %lf ms\n", (t2-t1)*1000);
}


Solution

  • As @Gilles pointed out in the comments under the question, the problem was with the x variable which was declared as a shared variable. it should be declared as a private variable.

    ...
    
    #pragma omp parallel
        {
            double x;
            double p_sum = 0.0;
    
            #pragma omp for
            for(i=0; i<num_steps; i++){
    
    ...