Python semaphore evevt生產(chǎn)者消費(fèi)者模型原理解析
線程鎖相當(dāng)于同時只能有一個線程申請鎖,有的場景無數(shù)據(jù)修改互斥要求可以同時讓多個線程同時運(yùn)行,且需要限制并發(fā)線程數(shù)量時可以使用信號量
import threading, time, queuedef test(name): semaphore.acquire() #獲取信號量鎖 print(’my name is %s’ %name) time.sleep(1) semaphore.release() #釋放信號量鎖semaphore = threading.BoundedSemaphore(5) #創(chuàng)建一個信號量同時可以運(yùn)行3個線程for i in range(20): t = threading.Thread(target=test, args=(i,)) t.start()while threading.active_count() == 1: print('all run done')
兩個或者多個線程需要交互時,且一個進(jìn)程需要根據(jù)另一線程狀態(tài)執(zhí)行對應(yīng)操作時,可以通過event來設(shè)置線程狀態(tài)達(dá)到期望的效果,下面是一個紅綠燈的例子
event = threading.Event() #實(shí)例化一個eventdef light(): while True: print('紅燈亮了,請停車') time.sleep(20) #開始是紅燈20s event.set() #紅燈時間到了,設(shè)置標(biāo)志位 print('綠燈亮了,請通行') time.sleep(30) #持續(xù)30s紅燈 event.clear() #清空標(biāo)志位def car(num): while True: if event.is_set():#檢測event被設(shè)置則執(zhí)行 print('car %s run'%num) time.sleep(5) else: print('this is red light waiting') event.wait() #此處會卡主,直到狀態(tài)被設(shè)置才會向下執(zhí)行Light = threading.Thread(target=light,)Light.start()for i in range(10): Car = threading.Thread(target=car, args=(i,)) Car.start()
當(dāng)多個線程需要交互數(shù)據(jù)可以使用queue來進(jìn)行數(shù)據(jù)傳遞,下面是經(jīng)典的生產(chǎn)者消費(fèi)者多線程模型示例,其中包含線程queue的基本使用方法
my_queue = queue.Queue() #實(shí)例化一個隊(duì)列queue1 = queue.LifoQueue() #后進(jìn) 先出隊(duì)列queue2 = queue.PriorityQueue() #帶優(yōu)先級的隊(duì)列def pro(): for i in range(100): my_queue.put(i) #隊(duì)列里面放數(shù)據(jù)def con(): while my_queue.qsize() > 0: #當(dāng)隊(duì)列有數(shù)據(jù)時候從隊(duì)列取數(shù)據(jù) print('i an a consumer,get num %s'%my_queue.get(timeout=3)) time.sleep(2) else: print('my queue is empty')Pro = threading.Thread(target=pro)Pro.start()for j in range(10): Con = threading.Thread(target=con) Con.start()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
