關(guān)于Python中幾種隊(duì)列Queue用法區(qū)別
python中使用到的隊(duì)列模塊大致有三個(gè):
1、from queue import Queue
此模塊適用于線程間通信,但不能用于進(jìn)程間通信。
示例代碼1: 【注意:此時(shí)代碼存在錯(cuò)誤!?。 ?/p>
import time
import threading
from queue import Queue
def task_func():
global queue
while queue.qsize() > 0:
x = queue.get()
print(f"num: {x}")
time.sleep(0.1)
def producer_data():
global queue
for i in range(100):
queue.put(i)
time.sleep(0.1)
if __name__ == '__main__':
queue = Queue()
producer_thread = threading.Thread(target=producer_data)
producer_thread.start()
thread_list = []
for i in range(5):
thread = threading.Thread(target=task_func)
thread.start()
thread_list.append(thread)
for thread in thread_list:
thread.join()
print("主程序執(zhí)行結(jié)束!")注意:上述寫法:
while queue.qsize() > 0:
x = queue.get()當(dāng)生產(chǎn)者速度沒有消費(fèi)者速度快時(shí),上述消費(fèi)者代碼會(huì)提前結(jié)束,導(dǎo)致生產(chǎn)者的速度不能消費(fèi)。
while True:
x = queue.get()這種寫法也存在問題,此時(shí)消費(fèi)者隊(duì)列會(huì)一直監(jiān)聽生產(chǎn)者隊(duì)列是否有數(shù)據(jù),導(dǎo)致線程一直處于阻塞狀態(tài),程序會(huì)一直阻塞不會(huì)停止,嚴(yán)重浪費(fèi)系統(tǒng)資源。如果使用apscheduler等定時(shí)任務(wù)的庫的話,會(huì)導(dǎo)致定時(shí)任務(wù)無法啟動(dòng)。
其實(shí)queue隊(duì)列中的put()或者get()方法中都提供了timeout參數(shù),利用這個(gè)參數(shù)可以有效解決上述消除不能消費(fèi)和線程一直阻塞問題。
示例代碼2:
import time
import threading
from queue import Queue
def task_func():
global queue
while True:
x = queue.get(timeout=10)
print(f"num: {x}")
def producer_data():
global queue
for i in range(100):
queue.put(i)
time.sleep(0.1)
if __name__ == '__main__':
queue = Queue()
producer_thread = threading.Thread(target=producer_data)
producer_thread.start()
thread_list = []
for i in range(5):
thread = threading.Thread(target=task_func)
thread.start()
thread_list.append(thread)
for thread in thread_list:
thread.join()
print("主程序執(zhí)行結(jié)束!")運(yùn)行結(jié)果:

根據(jù)不同的情境,可以根據(jù)實(shí)際情況設(shè)置timeout的值。如果使用定時(shí)任務(wù),使用timeout是可以的,不會(huì)使程序拋異常停止的。
2、from multiprocessing import Queue
此模塊用于對(duì)進(jìn)程,但是不能用于進(jìn)程池
示例代碼:
import time
from multiprocessing import Process, Queue
import queue
def producer(queue):
queue.put("a")
time.sleep(2)
def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)
if __name__ == "__main__":
# queue = queue.Queue()
queue = Queue()
my_producer = Process(target=producer, args=(queue, ))
my_consumer = Process(target=consumer, args=(queue, ))
my_producer.start()
my_consumer.start()
my_producer.join()
my_consumer.join()
# 使用queue模塊的Queue()會(huì)報(bào)錯(cuò)
# 使用multiprocessing中的Queue(),正確輸出a
運(yùn)行結(jié)果:

3、from multiprocessing import Manager
示例代碼:
import time
from multiprocessing import Process, Queue, Pool, Manager
def producer(queue):
queue.put("a")
time.sleep(2)
def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)
if __name__ == "__main__":
# queue = Queue()
queue = Manager().Queue()
pool = Pool()
# pool中的進(jìn)程間通信需要使用Manager
pool.apply_async(producer, args=(queue, ))
pool.apply_async(consumer, args=(queue, ))
pool.close()
pool.join()運(yùn)行結(jié)果:

到此這篇關(guān)于關(guān)于Python中幾種隊(duì)列Queue用法區(qū)別的文章就介紹到這了,更多相關(guān)Python中的隊(duì)列Queue內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python繪制帶有誤差棒條形圖的實(shí)現(xiàn)
本文主要介紹了python繪制帶有誤差棒條形圖的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
Python?OpenCV超詳細(xì)講解讀取圖像視頻和網(wǎng)絡(luò)攝像頭
OpenCV用C++語言編寫,它具有C?++,Python,Java和MATLAB接口,并支持Windows,Linux,Android和Mac?OS,OpenCV主要傾向于實(shí)時(shí)視覺應(yīng)用,并在可用時(shí)利用MMX和SSE指令,本篇文章帶你了解OpenCV讀取圖像視頻與網(wǎng)絡(luò)攝像頭的方法2022-04-04
用python做一個(gè)搜索引擎(Pylucene)的實(shí)例代碼
下面小編就為大家?guī)硪黄胮ython做一個(gè)搜索引擎(Pylucene)的實(shí)例代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實(shí)例
這篇文章主要介紹了numpy 矩陣形狀調(diào)整:拉伸、變成一位數(shù)組的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python3實(shí)現(xiàn)的zip格式壓縮文件夾操作示例
這篇文章主要介紹了python3實(shí)現(xiàn)的zip格式壓縮文件夾操作,結(jié)合實(shí)例形式分析了Python3基于zipfile模塊實(shí)現(xiàn)zip格式文件壓縮的相關(guān)操作技巧,需要的朋友可以參考下2019-08-08

