本文實例講述了python避免死鎖方法。分享給大家供大家參考。具體分析如下:
當兩個或者更多的線程在等待資源的時候就會產生死鎖,兩個線程相互等待。
在本文實例中 thread1 等待thread2釋放block , thread2等待thtead1釋放ablock,
避免死鎖的原則:
1. 一定要以一個固定的順序來取得鎖,這個列子中,意味著首先要取得alock, 然后再去block
2. 一定要按照與取得鎖相反的順序釋放鎖,這里,應該先釋放block,然后是alock
import threading ,timea = 5alock = threading.Lock()b = 5block = 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 athread2 acquiring lock bthread1 acquiring lock bthread2 acquiring lock a
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答