Operating SystemWindowsMCA

Deadlock can be occurred in a multithreaded Pthread program using mutex locks. Let’s see how it can be occurred. An unlocked mutex is initialized by the pthread_mutex_init() function.

Using pthread_mutex_lock() and pthread_mutex_unlock() Mutex locks are acquired and released. If a thread try to acquire a locked mutex, the call to pthread_mutex_lock() blocks the thread until the owner of the mutex lock invokes pthread_mutex_unlock().

Let’s take an example, two Mutex locks are created in the following Code −

/* Create and initialize the mutex locks */
pthread mutex init(&mutex2,NULL);

/* thread1 runs in this function */
void *dosomework_1(void *param) {
/**
* Do some work */
*/ void *dosomework_2(void *param) {
/**
* Do some work */
}

In this example, thread1 tries to acquire the mutex locks in the order

• mutex1,
• mutex2,

while thread two tries to acquire the mutex locks in the order

• mutex2,
• mutex1,

Deadlock is possible if thread1 acquires mutex1 while thread2 acquires mutex2. Even though deadlock is possible, it will not occur if thread1 can acquire and release the mutex locks for mutex1 and mutex2 before thread2 tries to acquire the locks. Of course, CPU scheduler scheduled the order in which the threads run. The above example illustrates a problem with handling deadlocks: it is difficult to identify and test for deadlocks that may occur only under certain scheduling circumstances.

Published on 11-Oct-2019 16:29:57