Question

I'm learning OpenMP by building a simple program to calculate pi using the following algorithm:

pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9...

The problem is that it does not work correctly when I change the scheduling to static. It works perfectly when the thread count is one. It also runs correctly under dynamic scheduling despite the result differing slightly every time it's run. Any idea what could be the problem?

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

#define N       100
#define CSIZE   1
#define nthread 2

int pi()
{
int i, chunk;
float pi = 0, x = 1;

chunk = CSIZE;
omp_set_num_threads(nthread);

#pragma omp parallel shared(i, x, chunk)
{
    if (omp_get_num_threads() == 0)
    {
        printf("Number of threads = %d\n", omp_get_num_threads());
    }

    printf("Thread %d starting...\n", omp_get_thread_num());

    #pragma omp for schedule(dynamic, chunk)
    for (i = 1; i <= N; i++)
    {
        if (i % 2 == 0)
            pi = pi - 4/x;
        else
            pi = pi + 4/x;

        x = x + 2;

        printf("Pi is currently %f at iteration %d with x = %0.0f on thread %d\n",
                pi, i, x, omp_get_thread_num());
    }
}

return EXIT_SUCCESS;
}
Was it helpful?

Solution

Using printf in the loop when I test your code makes dynamic do all the work on the first thread and none on the second (making the program effectively serial). If you remove the printf statement then you will find that the value of pi is random. This is because you have race conditions in x and pi.

Instead of using x you can divide by 2*i+1 (for i starting at zero). Also instead of using a branch to get the sign you can use sign = -2*(i%2)+1. To get pi you need to do a reduction using #pragma omp for schedule(static) reduction(+:pi).

#include <stdio.h>   
#define N 10000   
int main() {
    float pi;         
    int i;
    pi = 0;
    #pragma omp parallel for schedule(static) reduction(+:pi)
    for (i = 0; i < N; i++) {
        pi += (-2.0f*(i&1)+1)/(2*i+1);
    }
    pi*=4.0f;
    printf("%f\n", pi);   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top