先看一個很簡單的例子
1 #coding:utf8 2 import Queue 3 #queue是隊列的意思 4 q=Queue.Queue(maxsize=10) 5 #創建一個queue對象 6 for i in range(9): 7 q.put(i) 8 #放入元素 9 while not q.empty():#檢測元素是否為空 10 print q.get(),#讀取元素 11 #默認為先進先出
如果需要一個無限長或者先進后出的隊列
1 #創建一個無限長的隊列,如果maxsize小於1就表示隊列長度無限。 2 q1=Queue.Queue(-1) 3 #1、Python Queue模塊的FIFO隊列先進先出。 class Queue.Queue(maxsize) 4 #2、LIFO類似於堆,即先進后出。 class Queue.LifoQueue(maxsize) 5 #3、還有一種是優先級隊列級別越低越先出來。 class Queue.PriorityQueue(maxsize)
轉載 http://www.jb51.net/article/58004.htm
關於是否阻塞和timeout的問題
官方文檔:
-
Queue.
get
([block[, timeout]]) -
Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the
Empty
exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise theEmpty
exception (timeout is ignored in that case).刪除並且返回隊列里的一項。如果可選參數block是true,並且timeout是None,那么等到隊列里面沒有項時,會一直阻塞下去。如果block是true並且timeout為一個正數(單位是秒),那么在timeout秒之內沒有可用的項獲得,就會引發empty異常。如果block是false,那么不管timeout是多少,一旦沒有可用項,就會引發空異常。
put用法類似。
1 q2=Queue.Queue(3) 2 while not q2.full():#判斷q2隊列是否已滿 3 q2.put('hello') 4 print q2.get(block=True, timeout=1) 5 print q2.get(block=True, timeout=1) 6 print q2.get(block=True, timeout=1) 7 print q2.get(block=True, timeout=7) 8 9 ''' 10 hello 11 hello 12 hello 13 七秒后引發異常 14 Traceback (most recent call last): 15 File "queuetext.py", line 22, in <module> 16 print q2.get(block=True, timeout=7) 17 File "C:\Python27\lib\Queue.py", line 176, in get 18 raise Empty 19 ''' 20 #前面相同,將最后一句改為 21 print q2.get(block=True, timeout=None) 22 ''' 23 hello 24 hello 25 ''' 26 #前面相同,將最后一句改為 27 print q2.get(block=False, timeout=7) 28 ''' 29 hello 30 hello 31 hello 32 立即引發異常 33 Traceback (most recent call last): 34 File "queuetext.py", line 22, in <module> 35 print q2.get(block=True, timeout=7) 36 File "C:\Python27\lib\Queue.py", line 176, in get 37 raise Empty 38 '''
-
Queue.
get_nowait
() -
Equivalent to
get(False)
.
-