Search

Deadlock creation and avoidence in pthreads

In the post we saw how we can use mutex to prevent simultaneous usage of the same resource by multiple threads. But usage of mutexes have to be done very carefully to make sure that the threads don't end up in a dead lock.

A deadlock is a scenario when one thread is waiting for a resource which is held by the second thread, while the second thread is waiting for a resource held by the first thread. Thus causing both the threads to wait for each other infinitely.

To show how this situation might occur, in the following example we have used two mutexes,read_mutex and write_mutex. To gain access to the file both these mutexes have to be locked. In the code, the write thread locks write_mutex and then after a little delay tries to locks read_mutex. The read thread on the other hand locks read_mutex first and then tries to lock write_mutex.

Thus by the time the write tries to access read_mutex, it has already been locked by read thread and by the time read thread tries to lock write_mutex, it has already been locked by the write thread. Thus both the threads end up waiting infinitely for each other to unlock the mutexes and process ends up in a deadlock.



Save the file as mutex_deadlock.c, and compile it by passing "-lpthread" flag.



There will be no output as both the threads endup in a deadlock state, to get out of the execution use "cntrl + c".

To avoid such simple deadlocks the easiest method is to make sure that all the threads access the locks in a specific order. In the above example if it is made compulsory that every thread should lock write_mutex first and then try to lock read_mutex, then the deadlock situation will not occur as only one thread will get access to write_mutex first and the same thread will be able to access read_mutex too.

The above code modified to avoid deadlock is shown below. Note that the order of acquiring lock by both the threads is the same, thus able to prevent deadlock.



Save the code as mutex_nodeadlock.c, compile it using "-lpthread" flag.



Thus we can successfully avoid a potential deadlock situation, by making use of the rules order of locks.

Follow by Email