python避免死鎖方法實(shí)例分析
本文實(shí)例講述了python避免死鎖方法。分享給大家供大家參考。具體分析如下:
當(dāng)兩個或者更多的線程在等待資源的時候就會產(chǎn)生死鎖,兩個線程相互等待。
在本文實(shí)例中 thread1 等待thread2釋放block , thread2等待thtead1釋放ablock,
避免死鎖的原則:
1. 一定要以一個固定的順序來取得鎖,這個列子中,意味著首先要取得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
希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python爬蟲使用實(shí)例wallpaper問題記錄
本文介紹解決中文亂碼的方法,以及Python爬蟲處理數(shù)據(jù)、圖片URL的技巧,包括使用正則表達(dá)式處理字符串、URL替換等,還涉及單線程與多線程的應(yīng)用場景,如電腦壁紙和手機(jī)壁紙爬取,適合進(jìn)行Web數(shù)據(jù)抓取和處理的開發(fā)者參考2024-09-09
對python的bytes類型數(shù)據(jù)split分割切片方法
今天小編就為大家分享一篇對python的bytes類型數(shù)據(jù)split分割切片方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
python模塊和包的應(yīng)用BASE_PATH使用解析
這篇文章主要介紹了python模塊和包的應(yīng)用BASE_PATH使用解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12
在keras 中獲取張量 tensor 的維度大小實(shí)例
這篇文章主要介紹了在keras 中獲取張量 tensor 的維度大小實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python入門案例之找出文件中出現(xiàn)次數(shù)最多的10個單詞
這篇文章主要為大家?guī)硪粋€簡單的Python入門案例——找出文件中出現(xiàn)次數(shù)最多的10個單詞,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-02-02
ruff check文件目錄檢測--exclude參數(shù)設(shè)置路徑詳解
這篇文章主要為大家介紹了ruff check文件目錄檢測exclude參數(shù)如何設(shè)置多少路徑詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
python range()函數(shù)取反序遍歷sequence的方法
今天小編就為大家分享一篇python range()函數(shù)取反序遍歷sequence的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

