python多執行緒高階鎖condition簡單用法示例
阿新 • • 發佈:2020-01-09
本文例項講述了python多執行緒高階鎖condition簡單用法。分享給大家供大家參考,具體如下:
多執行緒程式設計中如果使用Condition物件代替lock,能夠實現在某個事件觸發後才處理資料,condition中含有的方法:
- - wait:執行緒掛起,收到notify通知後繼續執行
- - notify:通知其他執行緒,解除其它執行緒的wai狀態
- - notifyAll(): 通知所有執行緒
- - acquire和release: 獲得鎖和解除鎖,與lock類似,
- - enter和exit使得物件支援上下文操作:
def __enter__(self): return self._lock.__enter__() def __exit__(self,*args): return self._lock.__exit__(*args)
程式碼:
import threading from threading import Condition # condition class XiaoAi(threading.Thread): def __init__(self,cond): self.cond = cond super().__init__(name="xiaoai") def run(self): self.cond.acquire() self.cond.wait() print('{}:ennn. '.format(self.name)) self.cond.notify() self.cond.wait() print('{}:好嗒. '.format(self.name)) self.cond.release() class TianMao(threading.Thread): def __init__(self,cond): super().__init__(name="tiaomao") self.cond = cond def run(self): self.cond.acquire() print('{}:hello ~ xiaoai. '.format(self.name)) self.cond.notify() self.cond.wait() print('{}:我們來念一首詩吧! . '.format(self.name)) self.cond.notify() self.cond.release() if __name__ == '__main__': condition = Condition() xiaoai = XiaoAi(condition) tianmao = TianMao(condition) # 啟動順序很重要 xiaoai.start() tianmao.start()
列印結果:
tiaomao:hello ~ xiaoai.
xiaoai:ennn.
tiaomao:我們來念一首詩吧! .
xiaoai:好嗒
總結:
這個比較雞肋
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python程序與執行緒操作技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》、《Python+MySQL資料庫程式設計入門教程》及《Python常見資料庫操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。