#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main(int argc, char **argv)
{
unsigned long long in = 1;
unsigned long long total = 2;
double tol , change, new, secs , old = 0.0;
struct timeval start , end;
int threads ; /* ignored */
if ( argc < 2) {
exit (-1);
}
threads = atoi ( argv[1]);
tol = atof ( argv[2]);
if (( threads < 1) || ( tol < 0.0)) {
exit (-1);
}
tol = tol *tol;
srand48(clock());
gettimeofday (&start , NULL);
do
{
double x, y;
x = drand48();
y = drand48();
total ++;
if (( x*x + y*y) <= 1.00)
in ++;
new = 4.0 * (double)in/( double)total ;
change = fabs (new - old);
old = new;
}while (change > tol );
gettimeofday (&end, NULL);
secs = (( double)end.tv_sec - (double)start.tv_sec )
+ (( double)end.tv_usec - (double)start.tv_usec )/1000000.0;
printf ( ”Found estimate of pi of %.12f in %llu iterations , %.6f seconds.n n”,
new, total - 2, secs );
}
The code above is a sequential program that takes an argument for the tolerance for how closely to estimate pi. Once the change in these old and new values fall below the tolerance it exits.
I have to parallelize this program in pthreads. I am not trying to have someone do it for me but rather to get some pointers and ideas to think about so that I may be able to this. the pthreads program will take number of threads and tolerance as it's argument and output the estimation. I am very new to parallel programs and don't really know where to start so I will take any advice. Thanks.
Each thread should keep its own in and total counts and use a better exit condition. Then add up the in and total values from each thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With