python避免死結方法執行個體分析
本文執行個體講述了python避免死結方法。分享給大家供大家參考。具體分析如下:
當兩個或者更多的線程在等待資源的時候就會產生死結,兩個線程相互等待。
在本文執行個體中 thread1 等待thread2釋放block , thread2等待thtead1釋放ablock,
避免死結的原則:
1. 一定要以一個固定的順序來取得鎖,這個列子中,意味著首先要取得alock, 然後再去block
2. 一定要按照與取得鎖相反的順序釋放鎖,這裡,應該先釋放block,然後是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 a"
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 a"
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)
|
輸出:
?
|
1
2
3
4 |
thread1 acquiring lock a
thread2 acquiring lock b
thread1 acquiring lock b
thread2 acquiring lock a
|
希望本文所述對大家的Python程式設計有所協助。