Dead lock
When multiple resources are shared between threads, a deadlock can occur if the two thread holds a portion of the resources and waits for each other's resources at the same time. Although deadlocks rarely occur, they can cause the application to stop responding when they occur. Let's look at a deadlock example:
Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code
Execution Result:
Thread-1 got ResA
Thread-1 got Resb
Thread-1 got Resb
Thread-1 got ResA
Thread-2 got ResA
Thread-2 got Resb
Thread-2 got Resb
Thread-2 got ResA
Thread-3 got ResA
Thread-3 got Resb
Thread-3 got Resb
Thread-3 got ResA
Thread-5 got ResA
Thread-5 got Resb
Thread-5 got Resb
Thread-4 got ResA
At this point the process is dead.
Can be re-entered lock
A simpler deadlock scenario is a thread that "iterates" over the same resource, directly causing a deadlock:
Import threading
Import time
Class MyThread (threading. Thread):
def run (self):
Time.sleep (1)
If Mutex.acquire (1):
num = num+1
msg = self.name+ ' Set num to ' +str (num)
Print msg
Mutex.acquire ()
Mutex.release ()
Mutex.release ()
num = 0
Mutex = Threading. Lock ()
def test ():
For I in range (5):
t = MyThread ()
T.start ()
if __name__ = = ' __main__ ':
Test ()
To support multiple requests for the same resource in the same thread, Python provides a "reentrant lock": Threading. Rlock. Rlock internally maintains a lock and a counter variable, counter records the number of acquire, so that resources can be require multiple times. Until all the acquire of a thread are release, the other threads can get the resources. In the example above, if you use Rlock instead of lock, a deadlock will not occur:
Import threading
Import time
Class MyThread (threading. Thread):
def run (self):
Time.sleep (1)
If Mutex.acquire (1):
num = num+1
msg = self.name+ ' Set num to ' +str (num)
Print msg
Mutex.acquire ()
Mutex.release ()
Mutex.release ()
num = 0
Mutex = Threading. Rlock ()
def test ():
For I in range (5):
t = MyThread ()
T.start ()
if __name__ = = ' __main__ ':
Test ()
Execution Result:
Thread-1 Set num to 1
Thread-3 Set num to 2
Thread-2 Set num to 3
Thread-5 Set num to 4
Thread-4 Set num to 5
Python multithreaded Programming (3): Deadlocks and Reentrant locks