Mutual exclusion is an important concept in concurrent and parallel programming where different threads of execution cooperate to avoid causing racy program behavior. This exclusion is encapsulated at a high level in an object called a mutex. A mutex allows for protection of shared data by allowing cooperating threads to lock the mutex and thereby claim the exclusive use of critical data.
In this studio, you will:
Please complete the required exercises below, as well as any optional enrichment exercises that you wish to complete.
As you work through these exercises, please record your answers in a text file. When finished, submit your work via the git repository.
Make sure that the name of each person who worked on these exercises is listed in the first answer, and make sure you number each of your responses so it is easy to match your responses with each exercise.
pthread_mutex_tobject, initializing it, and then locking and unlocking this mutex around the critical section.
pthread_mutex_t object with the help of the man
man pthread_mutex_init. You may intialize your object
with the static initializer (
PTHREAD_MUTEX_INITIALIZER) or with
pthread_mutex_init() function (if you use this second
you can leave the
pthread_mutexattr_t pointer NULL).
Create this mutex inside your
main() function. Copy and paste your mutex creation code.
main()function to the
subtractor()functions from last time. Pass these pointers through the fourth parameter of
pthread_create(). Leave this answer blank.
pthread_mutex_unlock()to synchronize access to the racy variable. This means that your threads should not modify this variable unless they have successfully locked the mutex, and after modifying the variable they should unlock the mutex.
Run your program many times. Does your program output match your expectations? Copy and paste several program outputs.
timeutility. Copy and paste your program output, and calculate the average time.
Modify your program, if necessary, so that each thread locks and unlocks the mutex once per increment or decrement (that is, each thread should lock and unlock the mutex twenty million times. Take three time measurements, copy and paste your output, and compute the average. How much longer did this execution take?