since each thread has its own processing space


Since each thread has its own processing space therefore communication between threads will need to be done through a common global variable. Since multiple threads can access the same global variable this can leads to race condition. Therefore what we want is to protect the variable so that only one thread can access the variable at any time. In POSIX this is done via the mutual-exclusion variable, mutex. A mutex variable allow us to perform the lock/unlock action so that the critical section of the code can be protected.

A mutual exclusion variable is lock using the function call pthread_mutex_lock(&mutex_variable) and unlock using the function call pthread_mutex_unlock(&mutex_variable). When a mutex variable is locked any other thread attempt to lock it will be blocked and have to wait until the variable is being unlocked. A mutex variable is declared using the following syntax:

pthread_mutex_t mutex_variable=PTHREAD_MUTEX_INITIALIZER;

One problem of mutex is the possibility of deadlock if more than one resource is required for processing. Assume there are two mutexes in total being accessed by two separate threads. If each thread is allowed to lock only one of the two mutex that is required by each thread, then everything will be at a standstill while each thread wait for the other mutex to be unlocked. To see the effect of deadlock compile and run the program intro_mutex_deadlock.c. Does the thread terminate? The answer is no. It is because PrintProcess1 always lock mutex_lock_1 first then mutex_lock_2 while PrintProcess2 always does it in the reverse order. This is known as circular wait, which is one of the four necessary condition required for deadlock. Therefore when multiple mutex are involved the order of the mutex lock is very important. Modify the program so that PrintProcess2 lock the mutex in the same order as PrintProcess1. The deadlock should now be resolved and both threads can complete to termination.

(Note that this is one of the four conditions required for deadlock to occur: circular wait. As an exercise, list the other three necessary conditions for deadlock and identify which part of the intro_mutex_deadlock.c source code satisfies the condition. See if you can modify the program such that the deadlock can be avoided by eliminating each of the required condition.)

Request for Solution File

Ask an Expert for Answer!!
Operating System: since each thread has its own processing space
Reference No:- TGS0416922

Expected delivery within 24 Hours