python避免死鎖方法實例分析
更新時間:2015年06月04日 12:43:13 作者:MaxOmnis
這篇文章主要介紹了python避免死鎖方法,較為詳細的分析了死鎖的成因與避免形成死鎖的方法,需要的朋友可以參考下
本文實例講述了python避免死鎖方法。分享給大家供大家參考。具體分析如下:
當兩個或者更多的線程在等待資源的時候就會產生死鎖,兩個線程相互等待。
在本文實例中 thread1 等待thread2釋放block , thread2等待thtead1釋放ablock,
避免死鎖的原則:
1. 一定要以一個固定的順序來取得鎖,這個列子中,意味著首先要取得alock, 然后再去block
2. 一定要按照與取得鎖相反的順序釋放鎖,這里,應該先釋放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
希望本文所述對大家的Python程序設計有所幫助。
相關文章
ruff check文件目錄檢測--exclude參數設置路徑詳解
這篇文章主要為大家介紹了ruff check文件目錄檢測exclude參數如何設置多少路徑詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
python range()函數取反序遍歷sequence的方法
今天小編就為大家分享一篇python range()函數取反序遍歷sequence的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

