Python semaphore evevt生產(chǎn)者消費者模型原理解析
線程鎖相當于同時只能有一個線程申請鎖,有的場景無數(shù)據(jù)修改互斥要求可以同時讓多個線程同時運行,且需要限制并發(fā)線程數(shù)量時可以使用信號量
import threading, time, queue
def test(name):
semaphore.acquire() #獲取信號量鎖
print('my name is %s' %name)
time.sleep(1)
semaphore.release() #釋放信號量鎖
semaphore = threading.BoundedSemaphore(5) #創(chuàng)建一個信號量同時可以運行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ù)另一線程狀態(tài)執(zhí)行對應操作時,可以通過event來設置線程狀態(tài)達到期望的效果,下面是一個紅綠燈的例子
event = threading.Event() #實例化一個event
def light():
while True:
print("紅燈亮了,請停車")
time.sleep(20) #開始是紅燈20s
event.set() #紅燈時間到了,設置標志位
print("綠燈亮了,請通行")
time.sleep(30) #持續(xù)30s紅燈
event.clear() #清空標志位
def car(num):
while True:
if event.is_set():#檢測event被設置則執(zhí)行
print("car %s run"%num)
time.sleep(5)
else:
print("this is red light waiting")
event.wait() #此處會卡主,直到狀態(tài)被設置才會向下執(zhí)行
Light = threading.Thread(target=light,)
Light.start()
for i in range(10):
Car = threading.Thread(target=car, args=(i,))
Car.start()
當多個線程需要交互數(shù)據(jù)可以使用queue來進行數(shù)據(jù)傳遞,下面是經(jīng)典的生產(chǎn)者消費者多線程模型示例,其中包含線程queue的基本使用方法
my_queue = queue.Queue() #實例化一個隊列
queue1 = queue.LifoQueue() #后進 先出隊列
queue2 = queue.PriorityQueue() #帶優(yōu)先級的隊列
def pro():
for i in range(100):
my_queue.put(i) #隊列里面放數(shù)據(jù)
def con():
while my_queue.qsize() > 0: #當隊列有數(shù)據(jù)時候從隊列取數(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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pyppeteer執(zhí)行js繞過webdriver監(jiān)測方法下
這篇文章主要為大家介紹了pyppeteer上執(zhí)行js并繞過webdriver監(jiān)測常見方法的上篇,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04
python解析mdf或mf4文件利器之a(chǎn)sammdf用法
這篇文章主要介紹了python解析mdf或mf4文件利器之a(chǎn)sammdf用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
詳解PyCharm+QTDesigner+PyUIC使用教程
這篇文章主要介紹了詳解PyCharm+QTDesigner+PyUIC使用教程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06

