歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python 多線程之threading condition

Python 多線程之threading condition

日期:2017/3/1 9:38:37   编辑:Linux編程

使用Condition對象可以在某些事件觸發或者達到特定的條件後才處理數據,Condition除了具有Lock對象的acquire方法和release方法外,還有wait方法、notify方法、notifyAll方法等用於條件處理。

threading.Condition([lock]):創建一個condition,支持從外界引用一個Lock對象(適用於多個condtion共用一個Lock的情況),默認是創建一個新的Lock對象。

acquire()/release():獲得/釋放 Lock

wait([timeout]):線程掛起,直到收到一個notify通知或者超時(可選的,浮點數,單位是秒s)才會被喚醒繼續運行。wait()必須在已獲得Lock前提下才能調用,否則會觸發RuntimeError。調用wait()會釋放Lock,直至該線程被Notify()、NotifyAll()或者超時線程又重新獲得Lock.

notify(n=1):通知其他線程,那些掛起的線程接到這個通知之後會開始運行,默認是通知一個正等待該condition的線程,最多則喚醒n個等待的線程。notify()必須在已獲得Lock前提下才能調用,否則會觸發RuntimeError。notify()不會主動釋放Lock。

notifyAll(): 如果wait狀態線程比較多,notifyAll的作用就是通知所有線程(這個一般用得少)

舉例:

import threading
import time
L=[]
class boy(threading.Thread):
def __init__(self,cond,name = 'A boy'):

threading.Thread.__init__(self)
self.cond = cond
self.name = name
def run(self):
time.sleep(1)
'''boy start conversation, make sure
the girl thread stared before send notify'''
self.cond.acquire()
print self.name + ':Hello pretty~,I miss you\n'
self.cond.notify()
self.cond.wait()
print self.name + ':like moth missing fire\n'
self.cond.notify()
self.cond.wait()
print self.name + ':and I bought a gift for you in the list L\n'
L.append('channel5')
self.cond.notify()
self.cond.release()

class girl(threading.Thread):
def __init__(self,cond,name = 'A girl'):

threading.Thread.__init__(self)
self.cond = cond
self.name = name
def run(self):
self.cond.acquire()
self.cond.wait()
print self.name + ':Really, show me how much~\n'
self.cond.notify()
self.cond.wait()
print self.name +':you\'re so sweet~'
self.cond.notify()
self.cond.wait()
print self.name +':wow~~, that\'s '+L.pop()+'---the one I dreamed for so long, I love you'
self.cond.release()
if __name__ == '__main__':
cond = threading.Condition()
husband = boy(cond, 'Aidan')
wife = girl(cond,'PPP')
husband.start()
wife.start()
#husband.start()
husband.join() #wait untill these two threads end
wife.join()
print 'end converdarion\n'

Python向PHP發起GET與POST請求 http://www.linuxidc.com/Linux/2014-10/107903.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved