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