1. What is Deadlock?
Deadlock occurs when each thread in a group of threads is waiting for a condition that can
only be caused by another member of the the group. For example, given threads T1 and
T2, it is possible that T1 is holding a resource X while waiting for resource Y to become
available. Meanwhile, T2 is holding resource Y and is waiting for resource X to become
available. This condition is known, in the computing literature, as deadlock.
How to Know When Deadlock Has Hit You?
Aside from having to debug a distributed program, deadlock is perhaps one of the most
difficult programming errors to correct. At times, deadlock appears to behave almost like an
infinite loop. Sometimes, the program will appear to run normally by not “locking up.” Often,
the program will need to be run multiple times to even notice the problem. The tragedy of
it all is that the results are usually not reproducible nor consistent.
There are four ways in which deadlock can occur. To eliminate deadlock, all you need to do
is find a way to eliminate one of the conditions that can cause it. It is not always desirable to
eliminate a given condition. We will return to a discussion of this point shortly; however, we
consider here the possibility of eliminating a circular wait condition.
Four Conditions of Deadlock
Mutual exclusion: It must not be possible for more than one thread to use a resource at
the same time.
Hold and wait: Threads must hold resources and wait for others to become available.
Deadlock is not possible if no thread ever holds more than one resource at a time. Nor
is it possible if a thread can acquire more than one resource, but acquires all its
resources at one instant.
No preemption: It must not be possible to remove a resource from a thread that holds
it. Only the thread that holds a resource can give it up.
Circular wait: There must be a cycle of threads, each holding at least one resource and
waiting to acquire one of the resources that the next thread in the cycle holds.