python基礎 - 條件變量
阿新 • • 發佈:2018-04-13
con lock val CQ cond glob produce elf HR
有一類線程需要滿足條件之後才能夠繼續執行,Python提供了threading.Condition對象用於條件變量線程的支持,它除了能提供RLock()或Lock()的方法外,還提供了 wait()、notify()、notifyAll()方法。
lock_con=threading.Condition([Lock/Rlock]): 鎖是可選選項,不傳入鎖,對象自動創建一個RLock()。
- wait():條件不滿足時調用,線程會釋放鎖並進入等待阻塞
- notify():條件創造後調用,通知等待池激活一個線程
- notifyAll():條件創造後調用,通知等待池激活所有線程
import threading,time from random import randint class Producer(threading.Thread): def run(self): global L while True: val=randint(0,100) print(‘生產者‘,self.name,":Append"+str(val),L) if lock_con.acquire(): L.append(val) lock_con.notify() lock_con.release() time.sleep(3) class Consumer(threading.Thread): def run(self): global L while True: lock_con.acquire() if len(L)==0: lock_con.wait() print(‘消費者‘,self.name,":Delete"+str(L[0]),L) del L[0] lock_con.release() time.sleep(0.25) if __name__=="__main__": L=[] lock_con=threading.Condition() #創建條件變量鎖 threads=[] for i in range(5): threads.append(Producer()) threads.append(Consumer()) for t in threads: #啟動5個生產,1個消費線程對象 t.start() for t in threads: t.join()
python基礎 - 條件變量