這篇文章給大家分享的是有關(guān)Python實現(xiàn)條件變量同步的方法的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
創(chuàng)新互聯(lián)公司是專業(yè)的芙蓉網(wǎng)站建設(shè)公司,芙蓉接單;提供成都網(wǎng)站建設(shè)、網(wǎng)站制作,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行芙蓉網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
條件變量同步
有一類線程需要滿足條件之后才能夠繼續(xù)執(zhí)行,Python提供了threading.Condition 對象用于條件變量線程的支持,它除了能提供RLock()或Lock()的方法外,還提供了 wait()、notify()、notifyAll()方法。
lock_con=threading.Condition([Lock/Rlock]): 鎖是可選選項,不傳人鎖,對象自動創(chuàng)建一個RLock()。
wait():條件不滿足時調(diào)用,線程會釋放鎖并進入等待阻塞;
notify():條件創(chuàng)造后調(diào)用,通知等待池激活一個線程;
notifyAll():條件創(chuàng)造后調(diào)用,通知等待池激活所有線程。
import threading, time from random import randint class Producer(threading.Thread): def run(self): global L while True: val = randint(0, 100) print('生產(chǎn)者', 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 ----')
運行結(jié)果:
生產(chǎn)者 Thread-1 :Append63 [] 生產(chǎn)者 Thread-2 :Append66 [63] 生產(chǎn)者 Thread-3 :Append20 [63, 66] 生產(chǎn)者 Thread-4 :Append83 [63, 66, 20] 生產(chǎn)者 Thread-5 :Append2 [63, 66, 20, 83] 生產(chǎn)者 Thread-4 :Append26 [] 消費者 Thread-6 :Delete26 [26] 生產(chǎn)者 Thread-2 :Append21 [] 生產(chǎn)者 Thread-3 :Append71 [21] 生產(chǎn)者 Thread-1 :Append19 [21, 71] 生產(chǎn)者 Thread-5 :Append100 [21, 71, 19] 生產(chǎn)者 Thread-1 :Append96 [] 消費者 Thread-6 :Delete96 [96] ........
感謝各位的閱讀!關(guān)于Python實現(xiàn)條件變量同步的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
本文標題:Python實現(xiàn)條件變量同步的方法
分享URL:http://muchs.cn/article46/jcpphg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、虛擬主機、網(wǎng)站排名、營銷型網(wǎng)站建設(shè)、做網(wǎng)站、品牌網(wǎng)站設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)