python死锁案例_python避免死锁方法实例分析
本文實(shí)例講述了python避免死鎖方法。分享給大家供大家參考。具體分析如下:
當(dāng)兩個(gè)或者更多的線程在等待資源的時(shí)候就會(huì)產(chǎn)生死鎖,兩個(gè)線程相互等待。
在本文實(shí)例中 thread1 等待thread2釋放block , thread2等待thtead1釋放ablock,
避免死鎖的原則:
1. 一定要以一個(gè)固定的順序來取得鎖,這個(gè)列子中,意味著首先要取得alock, 然后再去block
2. 一定要按照與取得鎖相反的順序釋放鎖,這里,應(yīng)該先釋放block,然后是alock
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)
輸出:
thread1 acquiring lock a
thread2 acquiring lock b
thread1 acquiring lock b
thread2 acquiring lock a
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
本文標(biāo)題: python避免死鎖方法實(shí)例分析
本文地址: http://www.cppcns.com/jiaoben/python/125900.html
總結(jié)
以上是生活随笔為你收集整理的python死锁案例_python避免死锁方法实例分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 字符串原样输出程序python_Pyth
- 下一篇: 统计信号处理_声学前端:深度学习算法和传