Beneath are codes to help with the assignment It is possible to approximate the
ID: 3731002 • Letter: B
Question
Beneath are codes to help with the assignment
It is possible to approximate the number PI by throwing darts at a circle drawn within a square. Using this method, PI is four times the ratio of darts that manage to land within the circle. Approximateling PI in this way is an easily parallelizable algorithm that requires a minimum amount of communication between the threads. Your task is to correctly implement this algorithm to use many threads, modifying the provided single- threaded solution. To accomplish this, you only need to add pthread calls to the provided code, without changing much of the underlying algorithm. Note that, however, you will need to synchronize some of the code to prevent race conditions. You will be graded on both correctness and on synchronizing the minimally needed amount of code, therefore preserving performance.Explanation / Answer
To calculate PI using multi threads
1. Divided the task of counting hits ( z < 1) to different threads
2. Each thread will run their share of iterations and will count the hits
3. We will add hits of each thread to a global count when before returing from thread.
4. This way our task will be acheived and we can calculate PI = count / niter * 4
Here is complete program
compile it like this
gcc pi.c -o demo -pthread
and run
./demo
==============================
pi.c
===========
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <pthread.h>
#define SEED 35791246
#define NUM_THREADS 4
long iter_per_thread;
long global_incircle_count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *in_circle_counter() {
long count=0;
long j;
double x,y,z;
for(j=0;j<iter_per_thread;j++){
x=(double) rand()/RAND_MAX;
y=(double) rand()/RAND_MAX;
z=x*x+y*y;
if(z<1) count++;
}
pthread_mutex_lock(&mutex);
global_incircle_count += count;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[])
{
int niter=0;
int i;
double pi;
printf("Enter the number of iterations used to estimate pi:");
scanf("%d",&niter);
iter_per_thread = niter / NUM_THREADS;
srand (SEED);
pthread_t *threads = malloc(NUM_THREADS * sizeof(pthread_t));
pthread_attr_t attr;
pthread_attr_init(&attr);
for (i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], &attr, in_circle_counter, (void *) NULL);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
free(threads);
long iter_used = NUM_THREADS * iter_per_thread;
pi=(double) global_incircle_count/iter_used * 4;
printf("# of trials=%lu, estimate of pi is %g ", iter_used, pi);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.