How does a Python deadlock form?
Deadlock refers to two or more processes in the process of execution, because of the competition for resources caused by a mutual waiting phenomenon, if there is no external force, they will not go forward. At this point the system is in a deadlock state or the system generates a deadlock, and these processes, which are always waiting on each other, are called deadlock processes. Because the resource consumption is mutually exclusive, when a process requests resources, so that the process without external assistance, never allocated the necessary resources and can not continue to run, which creates a special phenomenon of deadlock.
‘‘‘
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 that acquire another competing resource after acquiring a competing resource, and we look at the result of the operation:
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
The program has been suspended there, and this phenomenon we call "deadlock."
Some of the code originates from Codego.net and is truncated.
The formation of the Python deadlock