8.10.Queue — A synchronized queue class

Note

TheQueue module has been renamed toqueue in Python 3. The2to3 tool will automatically adapt imports when converting yoursources to Python 3.

Source code:Lib/Queue.py


TheQueue module implements multi-producer, multi-consumer queues.It is especially useful in threaded programming when information must beexchanged safely between multiple threads. TheQueue class in thismodule implements all the required locking semantics. It depends on theavailability of thread support in Python; see thethreadingmodule.

The module implements three types of queue, which differ only in the order inwhich the entries are retrieved. In a FIFO queue, the first tasks added arethe first retrieved. In a LIFO queue, the most recently added entry isthe first retrieved (operating like a stack). With a priority queue,the entries are kept sorted (using theheapq module) and thelowest valued entry is retrieved first.

TheQueue module defines the following classes and exceptions:

classQueue.Queue(maxsize=0)

Constructor for a FIFO queue.maxsize is an integer that sets the upperboundlimit on the number of items that can be placed in the queue. Insertion willblock once this size has been reached, until queue items are consumed. Ifmaxsize is less than or equal to zero, the queue size is infinite.

classQueue.LifoQueue(maxsize=0)

Constructor for a LIFO queue.maxsize is an integer that sets the upperboundlimit on the number of items that can be placed in the queue. Insertion willblock once this size has been reached, until queue items are consumed. Ifmaxsize is less than or equal to zero, the queue size is infinite.

New in version 2.6.

classQueue.PriorityQueue(maxsize=0)

Constructor for a priority queue.maxsize is an integer that sets the upperboundlimit on the number of items that can be placed in the queue. Insertion willblock once this size has been reached, until queue items are consumed. Ifmaxsize is less than or equal to zero, the queue size is infinite.

The lowest valued entries are retrieved first (the lowest valued entry is theone returned bysorted(list(entries))[0]). A typical pattern for entriesis a tuple in the form:(priority_number,data).

New in version 2.6.

exceptionQueue.Empty

Exception raised when non-blockingget() (orget_nowait()) is calledon aQueue object which is empty.

exceptionQueue.Full

Exception raised when non-blockingput() (orput_nowait()) is calledon aQueue object which is full.

See also

collections.deque is an alternative implementation of unboundedqueues with fast atomicappend() andpopleft() operations thatdo not require locking.

8.10.1.Queue Objects

Queue objects (Queue,LifoQueue, orPriorityQueue)provide the public methods described below.

Queue.qsize()

Return the approximate size of the queue. Note, qsize() > 0 doesn’tguarantee that a subsequent get() will not block, nor will qsize() < maxsizeguarantee that put() will not block.

Queue.empty()

ReturnTrue 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’tguarantee that a subsequent call to get() will not block.

Queue.full()

ReturnTrue 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’tguarantee that a subsequent call to put() will not block.

Queue.put(item[,block[,timeout]])

Putitem into the queue. If optional argsblock is true andtimeout isNone (the default), block if necessary until a free slot is available. Iftimeout is a positive number, it blocks at mosttimeout seconds and raisestheFull exception if no free slot was available within that time.Otherwise (block is false), put an item on the queue if a free slot isimmediately available, else raise theFull exception (timeout isignored in that case).

New in version 2.3:Thetimeout parameter.

Queue.put_nowait(item)

Equivalent toput(item,False).

Queue.get([block[,timeout]])

Remove and return an item from the queue. If optional argsblock is true andtimeout isNone (the default), block if necessary until an item is available.Iftimeout is a positive number, it blocks at mosttimeout seconds andraises theEmpty 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:Thetimeout parameter.

Queue.get_nowait()

Equivalent toget(False).

Two methods are offered to support tracking whether enqueued tasks have beenfully processed by daemon consumer threads.

Queue.task_done()

Indicate that a formerly enqueued task is complete. Used by queue consumerthreads. For eachget() used to fetch a task, a subsequent call totask_done() tells the queue that the processing on the task is complete.

If ajoin() is currently blocking, it will resume when all items have beenprocessed (meaning that atask_done() call was received for every itemthat had beenput() into the queue).

Raises aValueError if called more times than there were items placed inthe queue.

New in version 2.5.

Queue.join()

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 callstask_done() toindicate that the item was retrieved and all work on it is complete. When thecount of unfinished tasks drops to zero,join() unblocks.

New in version 2.5.

Example of how to wait for enqueued tasks to be completed:

defworker():whileTrue:item=q.get()do_work(item)q.task_done()q=Queue()foriinrange(num_worker_threads):t=Thread(target=worker)t.daemon=Truet.start()foriteminsource():q.put(item)q.join()# block until all tasks are done