Python Queue模塊詳解
Python中,隊列是線程間最常用的交換數(shù)據(jù)的形式。Queue模塊是提供隊列操作的模塊,雖然簡單易用,但是不小心的話,還是會出現(xiàn)一些意外。
創(chuàng)建一個“隊列”對象
import Queue
q = Queue.Queue(maxsize = 10)
Queue.Queue類即是一個隊列的同步實現(xiàn)。隊列長度可為無限或者有限??赏ㄟ^Queue的構造函數(shù)的可選參數(shù)maxsize來設定隊列長度。如果maxsize小于1就表示隊列長度無限。
將一個值放入隊列中
q.put(10)
調(diào)用隊列對象的put()方法在隊尾插入一個項目。put()有兩個參數(shù),第一個item為必需的,為插入項目的值;第二個block為可選參數(shù),默認為
1。如果隊列當前為空且block為1,put()方法就使調(diào)用線程暫停,直到空出一個數(shù)據(jù)單元。如果block為0,put方法將引發(fā)Full異常。
將一個值從隊列中取出
q.get()
調(diào)用隊列對象的get()方法從隊頭刪除并返回一個項目??蛇x參數(shù)為block,默認為True。如果隊列為空且block為True,get()就使調(diào)用線程暫停,直至有項目可用。如果隊列為空且block為False,隊列將引發(fā)Empty異常。
Python Queue模塊有三種隊列及構造函數(shù):
1、Python Queue模塊的FIFO隊列先進先出。 class Queue.Queue(maxsize)
2、LIFO類似于堆,即先進后出。 class Queue.LifoQueue(maxsize)
3、還有一種是優(yōu)先級隊列級別越低越先出來。 class Queue.PriorityQueue(maxsize)
此包中的常用方法(q = Queue.Queue()):
q.qsize() 返回隊列的大小
q.empty() 如果隊列為空,返回True,反之False
q.full() 如果隊列滿了,返回True,反之False
q.full 與 maxsize 大小對應
q.get([block[, timeout]]) 獲取隊列,timeout等待時間
q.get_nowait() 相當q.get(False)
非阻塞 q.put(item) 寫入隊列,timeout等待時間
q.put_nowait(item) 相當q.put(item, False)
q.task_done() 在完成一項工作之后,q.task_done() 函數(shù)向任務已經(jīng)完成的隊列發(fā)送一個信號
q.join() 實際上意味著等到隊列為空,再執(zhí)行別的操作
范例:
實現(xiàn)一個線程不斷生成一個隨機數(shù)到一個隊列中(考慮使用Queue這個模塊)
實現(xiàn)一個線程從上面的隊列里面不斷的取出奇數(shù)
實現(xiàn)另外一個線程從上面的隊列里面不斷取出偶數(shù)
#!/usr/bin/env python #coding:utf8 import random,threading,time from Queue import Queue #Producer thread class Producer(threading.Thread): def __init__(self, t_name, queue): threading.Thread.__init__(self,name=t_name) self.data=queue def run(self): for i in range(10): #隨機產(chǎn)生10個數(shù)字 ,可以修改為任意大小 randomnum=random.randint(1,99) print "%s: %s is producing %d to the queue!" % (time.ctime(), self.getName(), randomnum) self.data.put(randomnum) #將數(shù)據(jù)依次存入隊列 time.sleep(1) print "%s: %s finished!" %(time.ctime(), self.getName()) #Consumer thread class Consumer_even(threading.Thread): def __init__(self,t_name,queue): threading.Thread.__init__(self,name=t_name) self.data=queue def run(self): while 1: try: val_even = self.data.get(1,5) #get(self, block=True, timeout=None) ,1就是阻塞等待,5是超時5秒 if val_even%2==0: print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(),self.getName(),val_even) time.sleep(2) else: self.data.put(val_even) time.sleep(2) except: #等待輸入,超過5秒 就報異常 print "%s: %s finished!" %(time.ctime(),self.getName()) break class Consumer_odd(threading.Thread): def __init__(self,t_name,queue): threading.Thread.__init__(self, name=t_name) self.data=queue def run(self): while 1: try: val_odd = self.data.get(1,5) if val_odd%2!=0: print "%s: %s is consuming. %d in the queue is consumed!" % (time.ctime(), self.getName(), val_odd) time.sleep(2) else: self.data.put(val_odd) time.sleep(2) except: print "%s: %s finished!" % (time.ctime(), self.getName()) break #Main thread def main(): queue = Queue() producer = Producer('Pro.', queue) consumer_even = Consumer_even('Con_even.', queue) consumer_odd = Consumer_odd('Con_odd.',queue) producer.start() consumer_even.start() consumer_odd.start() producer.join() consumer_even.join() consumer_odd.join() print 'All threads terminate!' if __name__ == '__main__': main()
相關文章
Python如何使用struct.unpack處理二進制文件
這篇文章主要介紹了Python如何使用struct.unpack處理二進制文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02Pytorch如何加載自己的數(shù)據(jù)集(使用DataLoader讀取Dataset)
這篇文章主要介紹了Pytorch如何加載自己的數(shù)據(jù)集(使用DataLoader讀取Dataset)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Python使用pydub模塊轉(zhuǎn)換音頻格式以及對音頻進行剪輯
這篇文章主要給大家介紹了關于Python使用pydub模塊轉(zhuǎn)換音頻格式以及對音頻進行剪輯的相關資料pydub是python的高級一個音頻處理庫,可以讓你以一種不那么蠢的方法處理音頻。需要的朋友可以參考下2021-06-06python requests 庫請求帶有文件參數(shù)的接口實例
今天小編就為大家分享一篇python requests 庫請求帶有文件參數(shù)的接口實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01對python3 sort sorted 函數(shù)的應用詳解
今天小編就為大家分享一篇對python3 sort sorted 函數(shù)的應用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06