2. 5.39 Exercise 4.22 asked you to design a multithreaded program that estimated π using the Monte
Carlo technique. In that exercise, you were asked to create a single thread that generated random
points, storing the result in a global variable. Once that thread exited, the parent thread performed the
calculation that estimated the value of π. Modify that program so that you create several threads, each
of which generates random points and determines if the points fall within the circle. Each thread will
have to update the global count of all points that fall within the circle. Protect against race conditions on
updates to the shared global variable by using mutex locks.
3. Monte Carlo estimation
The Monte Carlo technique, is also named Metropolis method, is a stochastic method that
generates random numbers to make a sample population of the system or different statistical
state of variable parameters in order to achieve statistically different materials properties.
Estimation of Pi
The idea is to simulate random (x, y) points in a 2-D plane with domain as a square of side 2r
units centered on (0,0). Imagine a circle inside the same domain with same radius r and
inscribed into the square. We then calculate the ratio of number points that lied inside the
circle and total number of generated points.
We know that area of the square is 4r^{2} unit sq while that of circle is pi r^{2} .
4. The ratio of these two areas is as follows :
To calculate the value of pi
pi= 4 * number of points in the circle
number of threads * number of points per thread
5. •In the main function, it creates THREAD_NUM number of
threads using the pthread_create function, each running the
inCircleCount function.
•The inCircleCount function, generates random points and
determines if the points fall within the circle by calling the
isInCircle function.
6. •Each thread then increments the global count of points within the circle using a mutex lock to
protect against race conditions.
•Once all threads have completed, the parent thread calculates the estimated value of π
and prints it to the console.
The pthread_join function is used to wait for each thread to complete, and the
pthread_mutex_destroy function is used to release the resources associated with the
mutex.
7. •The srand function is called in the generatePoints function, it seeds the
random number generator with the current time.
• This helps to ensure that the random number generator is generating
truly random numbers.
•You are also freeing the memory allocated for the tid array and
random_set after the threads have completed.