Dead Lock


Definition 


Task/Thread/Process is waiting to acquire the semaphore which will never become free.

                                   

Example 


Thread 1 acquires lock_1. It enters into for loop and waits for semaphore in function sem_wait(). At the same time, thread 2 acquires semaphore. 

In for loop, thread2 waits to acquire lock_1 which is already acquired by thread 1. But thread 1 has been waiting to get the semaphore which is acquired by thread 2.  This is a serious deadlock issue.




What are the causes of deadlock?

1. Forgetting to unlock.

Though most of the program does have the pair lock/unlock, it might not have the unlock at the error cases. 


How to prevent deadlock?

  1. Avoid having locksAlways take the locks in the same order. 
Consistent ordering of locking is pretty much the first and last word when it comes to deadlock avoidance.

The common solution to preventing deadlock in code is to make sure the sequence of locking occur in a common manner regardless of which thread is accessing the resources.

For example given threads T1 and T2, where T1 accesses resource A and then B and T2 accesses resource B and then A. Locking the resources in the order they are needed causes a dead-lock. The simple solution is to lock A and then lock B, regardless of the order specific thread will use the resources.

Problematic situation:

Thread1                         Thread2
-------                         -------
Lock Resource A                 Lock Resource B
 Do Resource A thing...          Do Resource B thing...
Lock Resource B                 Lock Resource A
 Do Resource B thing...          Do Resource A thing...

Possible Solution:

Thread1                         Thread2
-------                         -------
Lock Resource A                 Lock Resource A
Lock Resource B                 Lock Resource B
 Do Resource A thing...          Do Resource B thing...
 Do Resource B thing...          Do Resource A thing...
Deadlock can happen both in a multiprocessing or multithreading environment. I presume if there had been a deadlock between multi-threads that belong to one process, obviously the deadlock would have occurred between this process and the other. 

2. We cal also avoid using mechanisms like lock_guard, unique_lock, scoped_lock, etc.,
Click here to learn more about lock_guard.

lock_guard and unique_lock are pretty much the same thing; lock_guard is a restricted version with a limited interface.


lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.


So you always use lock_guard, unless you need the capabilities of unique_lock. A condition_variable needs a unique_lock.

How to detect?

jcmd $PID Thread.print
The above command can be executed only for java programming.

Reference :

vorbrodt.blog














Comments