1.the condition of deadlock
The code,
T1 is created. T1 first takes the lock of O1 and begins to sleep for 3 seconds. then
T2 thread created, T2 takes o2 lock and begins to sleep for 3 seconds. then
T1 wakes up first and prepares to take o2's lock, but finds that O2 has been locked and can only wait for O2's lock to be released.
Woke up after T2, ready to take the lock of O1, found that O1 has been locked, can only wait for the release of the lock of O1.
T1 and T2 form deadlocks.
Let's look at the result,
2.anlysis:
Conditions for deadlock generation:
Mutex: The lock on a resource is exclusive, and only one thread can own the resource during the lock. Other threads can only try to obtain the resource by waiting for the lock to be released. In this case, only one thread can proceed, and the others must be lighted.
Request and hold: The current thread already has at least one resource, but at the same time it makes a new resource request, and the requested resource is owned by another thread. At this point, you enter the state of holding the current resource and waiting for the next resource.
In this case, if T1 and T2 are created and T1 wants to take T2, it must wait for T2 to release itself.
Unstripping: Resources already owned by a thread can only be freed by itself and cannot be stripped by another thread.
Circular wait: Multiple threads that request each other's resources but also have the resources each other needs for the next step. Form a loop, similar to 2) request and hold. But this refers to a multi-thread relationship. It doesn't mean that a single thread is always waiting in the loop.
3. Solutions
Once a deadlock occurs, we can't solve it. So we can only avoid deadlock.
Since deadlocks need to satisfy four conditions, let's start with the conditions and just break any rule.
(Mutex) use the mutex as little as possible, can add a read lock, no write lock. This, of course, is unavoidable.
(Request and hold) adopt a resource static allocation policy (process resource static allocation means that a process allocates all the resources it needs when it is under construction). We try not to have threads request multiple locks at the same time, or if we have one lock and do not request the next lock, instead of waiting, we first release the resource and wait for some time before rerequesting it.
Allows a process to deprive the use of resources held by another process. Priority.
(circular wait) Try to adjust the order in which the locks are acquired so that nested resource requests do not occur. Add timeout.