OpenMP parallelization of pi computation is either slow or incorrect

I am having problems with the parallelism of my monte carlo method for computing pi. The following is a parallel loop:

#pragma omp parallel for private(i,x,y) schedule(static) reduction(+:count) for (i = 0; i < points; i++) { x = rand()/(RAND_MAX+1.0)*2 - 1.0; y = rand()/(RAND_MAX+1.0)*2 - 1.0; // Check if point lies in circle if(x*x + y*y < 1.0) { count++; } } 

The problem is that it underestimates pi if I use schedule(static) , and its slower than a sequential implementation if I use schedule(dynamic) . What am I doing wrong? I tried other ways to fix this (for example: Using OpenMP to calculate the PI value ), but it is still much slower than a sequential implementation.

Thank you in advance

+4
source share
2 answers

Assuming you are using a C rand library function, this function is not reentrant or thread safe. POSIX provides the rand_r function, but (to quote glibc documentation):

POSIX.1 extended the standard C functions to support reproducible random numbers in multi-threaded programs. However, the extension is poorly designed and unsuitable for serious work.

In particular, the seed must be an unsigned int that does not have enough bits for a good PRNG. They recommend using SVID random number functions, of which nrand48_r is probably what you are looking for.

Alternatively, you can use another library.

+6
source

One thing you should consider when doing these things in parallel is that there can be different rounding errors caused by different calculation methods.

Example:

((A+B) + (C+D)) , where (A+B) and (C+D) will be calculated in parallel, may differ from the sequential approach (((A+B) + C) + D) .

+1
source

Source: https://habr.com/ru/post/1392738/


All Articles