Python Deadlock Prevention Method Instance Analysis
This article describes how to avoid deadlocks in python. Share it with you for your reference. The specific analysis is as follows:
When two or more threads are waiting for resources, a deadlock occurs and the two threads wait for each other.
In this example, thread1 waits for thread2 to release the block, thread2 waits for thtead1 to release ablock,
The principle of avoiding deadlocks:
1. The lock must be obtained in a fixed order. In this column, the lock must be obtained first, and then block
2. The lock must be released in the order opposite to the lock obtained. Here, the block should be released first, and then the alock
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 |
Import threading, time
A = 5
Alock = threading. Lock ()
B = 5
Block = threading. Lock ()
Def thread1calc ():
Print "thread1 acquiring lock"
Alock. acquire ()
Time. sleep (5)
Print "thread1 acquiring lock B"
Block. acquire ()
A + = 5
B + = 5
Print "thread1 releasing both locks"
Block. release ()
Alock. release ()
Def thread2calc ():
Print "thread2 acquiring lock B"
Block. acquire ()
Time. sleep (5)
Print "thread2 acquiring lock"
Alock. acquire ()
Time. sleep (5)
A + = 10
B + = 10
Print "thread2 releasing both locks"
Block. release ()
Alock. release ()
T = threading. Thread (target = thread1calc)
T. setDaemon (1)
T. start ()
T = threading. Thread (target = thread2calc)
T. setDaemon (2)
T. start ()
While 1:
Time. sleep (300)
|
Output:
?
|
1
2
3
4 |
Thread1 acquiring lock
Thread2 acquiring lock B
Thread1 acquiring lock B
Thread2 acquiring lock
|
I hope this article will help you with Python programming.