Write a program using threads and mutexes by building on the program listing primes.c This program demonstrates basic pthread usage as well as the passing of parameters to and from a thread. In this case, main() generates a single thread that calculates the n'th prime and then returns it.

What you should do is generate 5 threads that share in the calculation of all the primes up to some limit. Please do the following:

  • Modify the program so that 5 threads are generated. See the file “thread-create.c” for an example of how to create a thread.
  • Each thread is passed a data structure that contains the thread's ID (0,1,2...) and a value for the maximum prime to calculate. See the file “thread-create2.c” for an example of how to pass a parameter to a thread.
  • Each thread should read the global integer 'master_list' for the prime to be calculated and then increment it for the next thread so that no prime is calculated more than once ('master_list' should have been previously initialized to 1). Since there are 5 threads, you will need to use mutexes when accessing master_list. See the “condvar.c” file for an example of using a mutex.
  • The subroutine compute_prime() is the function executed by the thread. Instead, write your own routine called void *prime_job(void *arg) (or whatever you want to call it) that is executed by the thread. Modify compute_prime() so that it is passed an integer (prime to calculate) and returns an integer ( the value of the prime).
  • Prime_job() should extract its ID and max prime value and then enter an endless loop that reads the master_list for a number, increments master_list, compares the number with the maximum value, and breaks out of the loop if the maximum is exceeded. Otherwise, it calls compute_prime(). Each thread should print its ID, the prime #, and the value of the prime. See the “thread-pid.c” program as an example for retrieving a thread’s PID value.
  • Each thread should keep a local counter of how many primes it actually got to calculate and return this value to main(). These count statistics should be printed out at the end of the program.
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.