這篇文章給大家分享的是有關Python實現條件變量同步的方法的內容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
條件變量同步
有一類線程需要滿足條件之后才能夠繼續執行,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: t.start() for t in threads: t.join() print('---- end ----')
運行結果:
生產者 Thread-1 :Append63 [] 生產者 Thread-2 :Append66 [63] 生產者 Thread-3 :Append20 [63, 66] 生產者 Thread-4 :Append83 [63, 66, 20] 生產者 Thread-5 :Append2 [63, 66, 20, 83] 生產者 Thread-4 :Append26 [] 消費者 Thread-6 :Delete26 [26] 生產者 Thread-2 :Append21 [] 生產者 Thread-3 :Append71 [21] 生產者 Thread-1 :Append19 [21, 71] 生產者 Thread-5 :Append100 [21, 71, 19] 生產者 Thread-1 :Append96 [] 消費者 Thread-6 :Delete96 [96] ........
感謝各位的閱讀!關于Python實現條件變量同步的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。