Python: Using the Threading module to implement multithreaded programming four [using lock mutex] we've started to deal with the use of mutexes to protect our public resources, and now consider the following scenarios –
If you have more than one public resource, when you share multiple resources between threads, what is the problem if two of them have separate resources and wait for each other's resources?
Deadlock concept
The so-called deadlock: refers to two or more than two processes in the implementation process, as a result of competing for resources caused by a mutual wait for the phenomenon, without external forces, they will not be able to push down. It is said that the system is in a deadlock state or the system produces a deadlock, and these processes that are always waiting for each other are called deadlock processes. Because the resource occupation is mutually exclusive, when a process to apply for resources, so that the process without external assistance, can never allocate the necessary resources and can not continue to run, which produces a special phenomenon deadlock.
Copy Code code as follows:
'''
Created on 2012-9-8
@author: walfred
@module: Thread. TreadTest5
'''
Import threading
Countera = 0
Counterb = 0
Mutexa = Threading. Lock ()
MUTEXB = Threading. Lock ()
Class Mythread (threading. Thread):
def __init__ (self):
Threading. Thread.__init__ (self)
def run (self):
SELF.FUN1 ()
Self.fun2 ()
def fun1 (self):
Global Mutexa, Mutexb
If Mutexa.acquire ():
Print "I am%s, get res:%s"% (Self.name, "ResA")
If Mutexb.acquire ():
Print "I am%s, get res:%s"% (Self.name, "Resb")
Mutexb.release ()
Mutexa.release ()
def fun2 (self):
Global Mutexa, Mutexb
If Mutexb.acquire ():
Print "I am%s, get res:%s"% (Self.name, "Resb")
If Mutexa.acquire ():
Print "I am%s, get res:%s"% (Self.name, "ResA")
Mutexa.release ()
Mutexb.release ()
if __name__ = = "__main__":
For I in range (0, 100):
My_thread = Mythread ()
My_thread.start ()
The code shows the two functional functions of a thread, respectively, after acquiring a competing resource, to gain additional competitive resources, we see the results of the operation:
Copy Code code as follows:
I am Thread-1, get Res:resa
I am Thread-1, get res:resb
I am Thread-2, get Res:resai am Thread-1, get res:resb
As you can see, the program has been suspended there, and this phenomenon is what we call a "deadlock".
Avoid deadlocks
The main way to avoid deadlocks is to allocate the resources correctly, and to avoid the most representative algorithm in the deadlock algorithm is the banker algorithm proposed by Dijkstra E.W in 1968.