python多線程高級鎖condition簡單用法示例
本文實例講述了python多線程高級鎖condition簡單用法。分享給大家供大家參考,具體如下:
多線程編程中如果使用Condition對象代替lock, 能夠?qū)崿F(xiàn)在某個事件觸發(fā)后才處理數(shù)據(jù), condition中含有的方法:
- - wait:線程掛起,收到notify通知后繼續(xù)運行
- - notify:通知其他線程, 解除其它線程的wai狀態(tài)
- - 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()
打印結(jié)果:
tiaomao:hello ~ xiaoai.
xiaoai:ennn.
tiaomao:我們來念一首詩吧! .
xiaoai:好嗒
總結(jié):
這個比較雞肋
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進(jìn)程與線程操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python中decimal.Decimal類型和float類型的比較
這篇文章主要介紹了Python中decimal.Decimal類型和float類型的比較,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
OpenCV物體跟蹤樹莓派視覺小車實現(xiàn)過程學(xué)習(xí)
這篇文章主要介紹了OpenCV物體跟蹤樹莓派視覺小車的實現(xiàn)過程學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10

