本文實例講述了python條件變量之生產(chǎn)者與消費者操作。分享給大家供大家參考,具體如下:
互斥鎖是最簡單的線程同步機制,面對復雜線程同步問題,Python還提供了Condition對象。Condition被稱為條件變量,除了提供與Lock類似的acquire和release方法外,還提供了wait和notify方法。線程首先acquire一個條件變量,然后判斷一些條件。如果條件不滿足則wait;如果條件滿足,進行一些處理改變條件后,通過notify方法通知其他線程,其他處于wait狀態(tài)的線程接到通知后會重新判斷條件。不斷的重復這一過程,從而解決復雜的同步問題。
可以認為Condition對象維護了一個鎖(Lock/RLock)和一個waiting池。線程通過acquire獲得Condition對象,當調用wait方法時,線程會釋放Condition內部的鎖并進入blocked狀態(tài),(但實際上不會block當前線程)同時在waiting池中記錄這個線程。當調用notify方法時,Condition對象會從waiting池中挑選一個線程,通知其調用acquire方法嘗試取到鎖。
Condition對象的構造函數(shù)可以接受一個Lock/RLock對象作為參數(shù),如果沒有指定,則Condition對象會在內部自行創(chuàng)建一個RLock。
線程同步經(jīng)典問題----生產(chǎn)者與消費者問題可以使用條件變量輕松解決。
import threading import time class 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 = 0 con = 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()
上面的代碼假定消費者消費的比較快,輸出結果為:
聲明:本網(wǎng)頁內容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com