I have two implementations of counting pi with the Monte Carlo method : with and without threads. A threadless implementation works very well, but the threading method has problems with accuracy and performance. Here is the code:
Without threads:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); unsigned long N = 0, Nin = 0; float x,y; while(N < 2E+9) { x = rand()/((float)RAND_MAX + 1.0)*10.0 - 5.0; y = rand()/((float)RAND_MAX + 1.0)*10.0 - 5.0; if(x*x + y*y < 25.0) Nin += 1; N++; } long double pi = 4.0 * (long double)Nin / (long double)N; printf("\tPi1: %.20Lf\n\t%lu %lu\n", pi, Nin, N); return 0; }
And with threads:
#include <stdio.h>
Results:
$ time ./pi2 Pi2: 3.14147154999999999995 1570735775 2000000000 real 1m1.927s user 1m23.624s sys 0m0.139s $ time ./pi Pi1: 3.14158868600000000006 1570794343 2000000000 real 0m49.956s user 0m49.887s sys 0m0.022s
Where is my mistake?
source share