The module has been renamed to queue
in Python 3. The tool will automatically adapt imports when converting your sources to Python 3.
Source code:
The module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the 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 module) and the lowest valued entry is retrieved first.
The 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 (or ) is called on a object which is empty.
Queue.
Empty
- exception
-
Exception raised when non-blocking (or ) is called on a object which is full.
Queue.
Full
See also
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 (, , or ) 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 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 the 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 exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the 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 used to fetch a task, a subsequent call to tells the queue that the processing on the task is complete.
If a is currently blocking, it will resume when all items have been processed (meaning that a call was received for every item that had been into the queue).
Raises a 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 to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, 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,挺好用。
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-8import threadingimport timefrom Queue import Queueclass 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生成产品5Thread-3消费了 初始产品0生成产品6生成产品7生成产品6生成产品8Thread-3消费了 初始产品1Thread-5消费了 初始产品2Thread-4消费了 初始产品3Thread-6消费了 初始产品4生成产品7Thread-7消费了 初始产品5生成产品9Thread-3消费了 初始产品6Thread-5消费了 初始产品7Thread-4消费了 初始产品8Thread-6消费了 初始产品9Thread-7消费了 初始产品10生成产品8生成产品10Thread-5消费了 初始产品11Thread-4消费了 初始产品12Thread-6消费了 初始产品13Thread-7消费了 初始产品14生成产品9生成产品11生成产品10生成产品12生成产品11生成产品13生成产品12生成产品13...