In multithreaded code, deadlock can occur when two threads each request a lock held by the other. For example, suppose that there are two threads (thread 1 and thread 2) and two mutexes (A and B). The following scenario is a deadlock:
thread 1 locks B thread 2 locks A thread 2 requests a lock on B thread 1 requests a lock on A
In this situation, both thread 1 and thread 2 wait forever for the requested locks.You can typically avoid deadlock by designing locking protocols for the application. These specify the order in which simultaneously held locks must be requested. In the scenario above, such a protocol might be stated: “If both mutex A and mutex B are taken, then A must be acquired first.”On some systems, a thread can deadlock with itself by requesting a lock that it already holds. Read your thread system documentation for the recommended practices to avoid deadlock.