- Computing the value of .
- Based on generating random numbers in a unit length square and counting the number of points that fall within the largest circle inscribed in the square.
- Since the area of the circle () is equal to , and the area of the square is
, the fraction of random points that fall in the circle should approach .
- Threaded strategy:
- assigns a fixed number of points to each thread.
- Each thread generates these random points and keeps track of the number of points in the circle locally.
- After all threads finish execution, their counts are combined to compute the value of (by calculating the fraction over all threads and multiplying by 4).
The arg field is used to pass an integer id that is used as a seed for randomization.
- For computing the value of ,
- First read in the desired number of threads, num_threads, and the desired number of sample points, sample_points.
- These points are divided equally among the threads.
- The program uses an array, hits, for assigning an integer id to each thread (this id is used as a seed for randomizing the random number generator).
- The same array is used to keep track of the number of hits (points inside the circle) encountered by each thread upon return.
- The program creates num_threads threads, each invoking the same function compute_pi, using the pthread_create function.
- Once the respective compute_pi threads have generated assigned number of random points and computed their hit ratios, the results must be combined to determine .
- Once all threads have joined, the value of is computed by multiplying the combined hit ratio by 4.0.
- The use of the function rand_r (instead of superior random number generators such as drand48).
- The reason for this is that many functions (including rand and drand48) are not reentrant.
Cem Ozdogan
2010-12-27