亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python多線程高級(jí)鎖condition簡(jiǎn)單用法示例

 更新時(shí)間:2019年11月07日 08:44:58   作者:weixin_42359464  
這篇文章主要介紹了python多線程高級(jí)鎖condition簡(jiǎn)單用法,結(jié)合實(shí)例形式分析了condition對(duì)象常用方法及相關(guān)使用技巧,需要的朋友可以參考下

本文實(shí)例講述了python多線程高級(jí)鎖condition簡(jiǎn)單用法。分享給大家供大家參考,具體如下:

多線程編程中如果使用Condition對(duì)象代替lock, 能夠?qū)崿F(xiàn)在某個(gè)事件觸發(fā)后才處理數(shù)據(jù), condition中含有的方法:

  • - wait:線程掛起,收到notify通知后繼續(xù)運(yùn)行
  • - notify:通知其他線程, 解除其它線程的wai狀態(tài)
  • - notifyAll(): 通知所有線程
  • - acquire和release: 獲得鎖和解除鎖, 與lock類似,
  • - enter和exit使得對(duì)象支持上下文操作:
  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('{}:我們來念一首詩(shī)吧! . '.format(self.name))
    self.cond.notify()
    self.cond.release()
if __name__ == '__main__':
  condition = Condition()
  xiaoai = XiaoAi(condition)
  tianmao = TianMao(condition)
  # 啟動(dòng)順序很重要
  xiaoai.start()
  tianmao.start()

打印結(jié)果:

tiaomao:hello ~ xiaoai.
xiaoai:ennn.
tiaomao:我們來念一首詩(shī)吧! .
xiaoai:好嗒

總結(jié):

這個(gè)比較雞肋

更多關(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ù)庫(kù)程序設(shè)計(jì)入門教程》及《Python常見數(shù)據(jù)庫(kù)操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論