Causes of deadlocks and quick location of deadlocks

Table of contents

Four factors that cause deadlock

 resolve deadlock

Quickly locate the process that caused the deadlock


Deadlock: The blocking phenomenon caused by concurrent threads waiting for each other's resources

Four factors that cause deadlock

1. Mutual exclusion: shared resources can only be occupied by one thread (mutual exclusion lock)

2. Possess and wait: The thread currently occupies at least one resource and wants to request other resources held by other threads, which will cause waiting (waiting for the other party to release the resource)

3. Non-preemption: The resource can only be released voluntarily by the thread holding it, and other threads cannot forcibly occupy the resource (the other party's resource cannot be released)

4. Circular waiting: thread t1 waits for the resources occupied by thread t2, and thread t2 waits for the resources occupied by thread t1, which is circular waiting (two threads wait for each other)

 resolve deadlock

When a deadlock occurs, the above four factors will be satisfied at the same time. If you want to prevent the occurrence of deadlock, destroy any one of the conditions.

1. Do not use mutex

2. Put two resources into a container, and when the resource is used by a process, another process will wait in a loop.

3. Lock timeout mechanism, automatically release resources after timeout

4. Mark resources and unlock resources in an orderly manner.

Eliminating deadlocks is trying to destroy at least one of the four necessary conditions for deadlocks. Strictly prevent the occurrence of deadlocks, while avoiding deadlocks does not strictly limit the existence of the necessary conditions for deadlocks, because even deadlocks A necessary condition exists, and a deadlock does not necessarily occur. Deadlock avoidance is to pay attention to avoid the eventual occurrence of deadlock during system operation.

In actual development, it is rare to completely eliminate the occurrence of deadlocks (affecting performance), and try to avoid the occurrence of deadlocks as much as possible.

Using the banker's algorithm can effectively avoid deadlocks, and the throughput performance of the system can also be guaranteed to a certain extent

Quickly locate the process that caused the deadlock

1. Open the command line window

 2. Find the process id of the current program

3. Print out the deadlocked process by command jstack+process id

 4. After pressing Enter, a deadlock is found, and the process stack of the deadlock is displayed

5. Read the information of the process stack: the resources waiting for t2 are locked by t1, and the resources waiting for t1 are locked by t2. deadlock

Guess you like

Origin blog.csdn.net/xzxailh/article/details/128992989