Calculate the value of PI Using Monte Carlo simulation and multithreading. Write
ID: 3763347 • Letter: C
Question
Calculate the value of PI Using Monte Carlo simulation and multithreading. Write a multithreaded program in c and name it ( multithread.c) that takes the following inputs as command line options:
-h: Print help message
-v Optional verbose flag (debugging print statements)
-t (num): Number of threads 2
-d (num): Number of darts
The threads will count the number of points that occur within the circle and store that result in a global variable. When the thread has exited, the parent thread will calculate and output the estimated value of . It is worth experimenting with the number of random points (Number
Explanation / Answer
#include <semaphore.h>
#include <unistd.h>
#include <iomanip>
#include <cmath>
#include <pthread.h>
#include <iostream>
#include <stdlib.h>
const t = 4;
struct Info
{
Info() : pi(0) {}
unsigned pi;
};
void* func(void* param)
{
double pi, v = 0,
xValue,
yValue,
h=1000000,
d;
srand(time(ULL));
if (Info* info = static_cast<Info*>(param))
{
for(int info=0; info<h; info++)
{
xValue = (double) rand()/RAD_MAX; //Random point: x
yValue = (double) rand()/RAD_MAX; //Random point: y
d = (xValue * xValue) + (yValue * yValue);
if(d <= 1.0)
++v;
}
pi = 4.0 * vTotal/(4 * h);
}
return param;
}
int main()
{
srand(time(ULL));
pthread_t handles[];
Info info[];
// start the threads
for (t i = 0; i != 4; ++i)
pthread_create(&handles[i], ULL, func, &info[i]);
// wait for the threads to complete
for (t i = 0; i != 4; ++i)
pthread_join(handles[i], ULL);
// process the reply
for (t i = 0; i != 4; ++i)
std::cout << "value[" << i << "] = " << info[i].pi << std::endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.