Primary patterns used¶
The important patterns to envision in this code are:
SPMD, since we have one program that multiple processes all run.
Data decomposition, since each process will compute an equal share of the total number of points requested.
Parallel for loop split with equal chunks computed by each process (inside the function called Toss()).
Reduction communication pattern to combine the results from each process.
There is also a broadcast from process 0. See if you can find that and what it was used for.
We start with this relatively straightforward example to illustrate that most MPI applications contain several patterns like this.
Here are some things to note about this code:
The function called Toss is named that because choosing the numbers is like tossing a dart at the square. Though our use of random numbers makes the tosses far more uniform than a human on a real board.
The command line argument is the number of random ‘tosses’ to generate.
We illustrate the block-splitting approach for delving out random numbers to the processes. The default value of 200000 tosses is divisible by 2, 4, and 8 threads so that this will work. We have a check to make sure that the number of tosses is divisible by the number of processes chosen.
We use the -Ofast compiler flag because in our experience the trng random number generator functions seem to perform better using this.
Exercises
Try increasing the number of tosses from 200000 to 2000000, then 20000000, then 200000000, and finally 2000000000 by adding a 0 each time and re-running with 4 or 8 processes. Does the estimated value of pi get more accurate as you increase the number of tosses? NOTE: random number generators have a limit of how many numbers they can generate. If you try too many, it will fail mysteriously.
For a challenge: Try changing to the leapfrog method for generating the random values, using the method called ‘split’. Revisit how this was done in Chapter 3.
For a challenge: Try using a different random number generation class from the trng library other than yarn2.