| Homework Two | |
Pthread Program One
The goal of this assignment is learn basic thread programming and to develop a program using the master/slave programming model. You will use mutex locks to avoid race conditions on data shared by several threads. Using the master/slave "Second model" pseudocode as as a starting point, write a C or C++ program using the pthread library as follows:
ParallelPrimes (print a usage message and exit)
ParallelPrimes number (execute the program with a default of 2 threads)
ParallelPrimes number numthreads (execute the program with numthreads)
The first paramater, number, is
the largest number that the program will test for
primality. The program will test all numbers from 2 up to
the entered number.
If number is not specified then the program should print a usage
message and exit.
The numthreads parameter gives the number of threads that
should be created. Use a default value of 2 for the number of
theads that are created.
Note: a number is prime if it is not divisible by any numbers other
than 1 and itself. For example, numbers up to 10 that are prime
include 2, 3, 5, and 7.
Note that this program is not very efficient. Don't worry about it for Program One. See Program Two below!
Test input data:
Pthread Program Two
The goal of this program is to make the multithreaded prime calculation more efficient.
Using your code from the previous program, write a program efficientPrimes that starts a fixed number of threads, as in the previous assignment, to determine the primality of all numbers in a range, but is more efficient. For example, when a thread enters the critical section to mark off that x is prime, the thread may also mark off 2x, 3x, 5x, 7x, 11x, etc., as ``taken'' and not prime. You may want to add other optimizations as well.
Have main echo the command line argument information to the screen. When each thread starts, print out a message, and also at each time that a number is taken, have the thread print out its name and the number it has just taken.
Be careful about race conditions! Make your code as efficient as you can, that is, try to have threads duplicate work as little as possible. But don't have a nervous breakdown trying to squeeze out every last microsecond. Also, try to keep the parallelism as great as possible. Since only one thread at a time can be in the synchronized block, make sure that a thread is in there for as little time as necessary.
To check your efficiency, add a call to time your code to determine how long your program ran.
Use the same test input data as in the previous assignment. You may add other test data, if you wish.
For this program we may give a prize to the program that executes in the shortest amount of time. We will definitely do this if there is a clear winner!
For both programs answer the following summary questions in a plain text file: