The Queue
module has been renamed to queue
in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
Source code: Lib/Queue.py
The Queue
module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue
class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading
module.
The module implements three types of queue, which differ only in the order in which the entries are retrieved. In a FIFO queue, the first tasks added are the first retrieved. In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack). With a priority queue, the entries are kept sorted (using the heapq
module) and the lowest valued entry is retrieved first.
The Queue
module defines the following classes and exceptions:
-
class
-
Constructor for a FIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
Queue.
Queue
(
maxsize=0
)
-
class
-
Constructor for a LIFO queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
New in version 2.6.
Queue.
LifoQueue
(
maxsize=0
)
-
class
-
Constructor for a priority queue. maxsize is an integer that sets the upperbound limit on the number of items that can be placed in the queue. Insertion will block once this size has been reached, until queue items are consumed. If maxsize is less than or equal to zero, the queue size is infinite.
The lowest valued entries are retrieved first (the lowest valued entry is the one returned by
sorted(list(entries))[0]
). A typical pattern for entries is a tuple in the form:(priority_number, data)
.New in version 2.6.
Queue.
PriorityQueue
(
maxsize=0
)
-
exception
-
Exception raised when non-blocking
get()
(orget_nowait()
) is called on aQueue
object which is empty.
Queue.
Empty
-
exception
-
Exception raised when non-blocking
put()
(orput_nowait()
) is called on aQueue
object which is full.
Queue.
Full
See also
collections.deque
is an alternative implementation of unbounded queues with fast atomic append()
and popleft()
operations that do not require locking.
8.10.1. Queue Objects
Queue objects (Queue
, LifoQueue
, or PriorityQueue
) provide the public methods described below.
-
Return the approximate size of the queue. Note, qsize() > 0 doesn’t guarantee that a subsequent get() will not block, nor will qsize() < maxsize guarantee that put() will not block.
Queue.
qsize
(
)
-
Return
True
if the queue is empty,False
otherwise. If empty() returnsTrue
it doesn’t guarantee that a subsequent call to put() will not block. Similarly, if empty() returnsFalse
it doesn’t guarantee that a subsequent call to get() will not block.
Queue.
empty
(
)
-
Return
True
if the queue is full,False
otherwise. If full() returnsTrue
it doesn’t guarantee that a subsequent call to get() will not block. Similarly, if full() returnsFalse
it doesn’t guarantee that a subsequent call to put() will not block.
Queue.
full
(
)
-
Put item into the queue. If optional args block is true and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the
Full
exception if no free slot was available within that time. Otherwise (block is false), put an item on the queue if a free slot is immediately available, else raise theFull
exception (timeout is ignored in that case).New in version 2.3: The timeout parameter.
Queue.
put
(
item
[,
block
[,
timeout
]
]
)
-
Equivalent to
put(item, False)
.
Queue.
put_nowait
(
item
)
-
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).New in version 2.3: The timeout parameter.
Queue.
get
(
[
block
[,
timeout
]
]
)
-
Equivalent to
get(False)
.
Queue.
get_nowait
(
)
Two methods are offered to support tracking whether enqueued tasks have been fully processed by daemon consumer threads.
-
Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each
get()
used to fetch a task, a subsequent call totask_done()
tells the queue that the processing on the task is complete.If a
join()
is currently blocking, it will resume when all items have been processed (meaning that atask_done()
call was received for every item that had beenput()
into the queue).Raises a
ValueError
if called more times than there were items placed in the queue.New in version 2.5.
Queue.
task_done
(
)
-
Blocks until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls
task_done()
to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero,join()
unblocks.New in version 2.5.
Queue.
join
(
)
Example of how to wait for enqueued tasks to be completed:
python原生的list,dict等,都是not thread safe的。而queue,是线程安全的。Queue.Queue类即是一个队列的同步实现。今天有个需求,典型的“生产者消费者问题”,刚好可以用到queue,挺好用。
python queue模块有三种队列:
1、python queue模块的FIFO队列先进先出。
2、LIFO类似于堆。即先进后出。
3、还有一种是优先级队列级别越低越先出来。
针对这三种队列分别有三个构造函数:
1、class Queue.Queue(maxsize) FIFO
2、class Queue.LifoQueue(maxsize) LIFO
3、class Queue.PriorityQueue(maxsize) 优先级队列
介绍一下此包中的常用方法:
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应
Queue.get([block[, timeout]])获取队列,timeout等待时间
Queue.get_nowait() 相当Queue.get(False)
非阻塞 Queue.put(item) 写入队列,timeout等待时间
Queue.put_nowait(item) 相当Queue.put(item, False)
Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
Queue.join() 实际上意味着等到队列为空,再执行别的操作
这个例子很好,参考至网上:
#!/home/oracle/dbapython/bin/python #encoding=utf-8 import threading import time from Queue import Queue class Producer(threading.Thread): def run(self): global queue count = 0 while True: for i in range(100): if queue.qsize() > 1000: pass else: count = count +1 msg = '生成产品'+str(count) queue.put(msg) print msg time.sleep(1) class Consumer(threading.Thread): def run(self): global queue while True: for i in range(3): if queue.qsize() < 50: pass else: msg = self.name + '消费了 '+queue.get() print msg time.sleep(1) queue = Queue() def test(): for i in range(100): msg='初始产品'+str(i) print msg queue.put(msg) for i in range(2): p = Producer() p.start() for i in range(5): c = Consumer() c.start() if __name__ == '__main__': test()
执行下,结果如下,自己试一下吧。
$ ./queue.py 初始产品0 初始产品1 初始产品2 初始产品3 初始产品4 初始产品5 初始产品6 初始产品7 初始产品8 ... 初始产品92 初始产品93 初始产品94 初始产品95 初始产品96 初始产品97 初始产品98 初始产品99 生成产品1 生成产品2 生成产品3 生成产品4 生成产品1 生成产品2 生成产品3 生成产品4 生成产品5 生成产品5 Thread-3消费了 初始产品0 生成产品6 生成产品7 生成产品6 生成产品8 Thread-3消费了 初始产品1 Thread-5消费了 初始产品2 Thread-4消费了 初始产品3 Thread-6消费了 初始产品4 生成产品7Thread-7消费了 初始产品5 生成产品9 Thread-3消费了 初始产品6 Thread-5消费了 初始产品7 Thread-4消费了 初始产品8 Thread-6消费了 初始产品9 Thread-7消费了 初始产品10 生成产品8 生成产品10 Thread-5消费了 初始产品11 Thread-4消费了 初始产品12 Thread-6消费了 初始产品13 Thread-7消费了 初始产品14 生成产品9生成产品11 生成产品10 生成产品12 生成产品11 生成产品13生成产品12 生成产品13 ...