Monday, September 12, 2022

Dead lock sample code

Ref: https://www.tutorialspoint.com/deadlock-with-mutex-locks 


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 t mutex1;
pthread mutex t mutex2; pthread mutex init(&mutex1,NULL);
pthread mutex init(&mutex2,NULL);

Next, two threads - thread1 and thread2 - are created, and both these threads have access to both mutex locks. Thread1 and thread2 run in the functions dosomework_1 and dosomework_2, respectively, as shown below −

/* thread1 runs in this function */
void *dosomework_1(void *param) {
   pthread mutex lock(&mutex1);
   pthread mutex lock(&mutex2);
   /**
   * Do some work */
   pthread mutex unlock(& mutex2);
   pthread mutex unlock(& mutex2);
   pthread exit(0); } /*
   thread2 runs in this function
   */ void *dosomework_2(void *param) {
      pthread mutex lock(&mutex2);
      pthread mutex lock(&mutex1);
   /**
   * Do some work */
   pthread mutex unlock(&mutex1);
   pthread mutex unlock(&mutex2);
   pthread exit(0);
}

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.


Ref2: https://docs.oracle.com/cd/E19120-01/open.solaris/816-5137/6mba5vq11/index.html

No comments:

Post a Comment