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