ExcellentProgramThe clerk keeps pondering every lineCodeAnd its derivative effects, so excellent code is always very simple and efficient. When writing multi-threaded Synchronous Code blocks, we must consider possible deadlocks. Once a deadlock occurs, the related thread enters the wireless waiting state, which may cause the entire program to be unresponsive. Generally, the deadlock issue is very hidden. When designing a program, you must analyze the lock wait relationships between threads in detail.
Images from the Internet
There are four conditions for deadlock generation, and a deadlock may occur only when both conditions are met.
- Mutex conditions:Scheduling the allocated resources. That is, a resource is occupied by only one process within a period of time. If there are other processes requesting resources at this time, the requester can only wait until the processes occupying the resources are released after use.
- Request and retention conditions:This means that a process has maintained at least one resource, but has made new resource requests, and the resource has been occupied by other processes. At this time, the request process is blocked, however, you cannot release other resources that you have obtained.
- Non-deprivation conditions:Resources obtained by a process cannot be deprived before they are used up. They can only be released by themselves when they are used up.
- Loop wait condition:When a deadlock occurs, there must be a process-a circular chain of resources, that is, a process set {P0, P1, P2 ,···, p0 in PN} is waiting for resources occupied by P1; P1 is waiting for resources occupied by P2 ,......, PN is waiting for resources occupied by P0.
Since we know the necessary conditions for deadlock generation, we can avoid deadlock as long as we can avoid one or more deadlocks at will. We can set some restrictions to prevent deadlock in advance. We will not discuss how to detect and remove deadlocks for the moment.