A deadlock occurs when a thread holding a resource is waiting for a resource held by another thread, while that thread is also waiting for the first thread's resource. Any number of threads can be involved in a deadlock if there is at least one resource per thread. A thread can deadlock on itself. Other threads can also become blocked waiting for resources involved in the deadlock.
Following are two techniques you can use to avoid deadlocks:
Associate a sequence number with each mutex and lock mutexes in sequence. Never attempt to lock a mutex with a sequence number lower than that of a mutex the thread already holds.
If a thread needs to acquire a mutex with a lower sequence number, it must first release all mutexes with a higher sequence number (after ensuring that the protected data is in a consistent state).
This method is useful when a thread needs to lock the same mutex more than once before unlocking it. This technique can help prevent a thread from deadlocking on itself.