python Queue模块

先看一个很简单的例子

 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 the Empty 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).

posted @ 2016-04-21 17:17  dreamfor  阅读(3843)  评论(0编辑  收藏  举报