本文實例講述了python條件變量之生產者與消費者操作。分享給大家供大家參考,具體如下:
互斥鎖是最簡單的線程同步機制,面對復雜線程同步問題,Python還提供了Condition對象。Condition被稱為條件變量,除了提供與Lock類似的acquire和release方法外,還提供了wait和notify方法。線程首先acquire一個條件變量,然后判斷一些條件。如果條件不滿足則wait;如果條件滿足,進行一些處理改變條件后,通過notify方法通知其他線程,其他處于wait狀態的線程接到通知后會重新判斷條件。不斷的重復這一過程,從而解決復雜的同步問題。
可以認為Condition對象維護了一個鎖(Lock/RLock)和一個waiting池。線程通過acquire獲得Condition對象,當調用wait方法時,線程會釋放Condition內部的鎖并進入blocked狀態,(但實際上不會block當前線程)同時在waiting池中記錄這個線程。當調用notify方法時,Condition對象會從waiting池中挑選一個線程,通知其調用acquire方法嘗試取到鎖。
Condition對象的構造函數可以接受一個Lock/RLock對象作為參數,如果沒有指定,則Condition對象會在內部自行創建一個RLock。
線程同步經典問題----生產者與消費者問題可以使用條件變量輕松解決。
import threadingimport timeclass Producer(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global count while True: con.acquire() if count <20: count += 1 print self.name," Producer product 1,current is %d" %(count) con.notify() else: print self.name,"Producer say box is full" con.wait() con.release() time.sleep(1)class Consumer(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global count while True: con.acquire() if count>4: count -=4 print self.name,"Consumer consume 4,current is %d" %(count) con.notify() else: con.wait() print self.name," Consumer say box is empty" con.release() time.sleep(1)count = 0con = threading.Condition()def test(): for i in range(1): a = Consumer() a.start() for i in range(1): b =Producer() b.start()if __name__=='__main__': test()
上面的代碼假定消費者消費的比較快,輸出結果為:

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結》、《Python Socket編程技巧總結》、《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
|
新聞熱點
疑難解答
圖片精選