queue — A synchronized queue class

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.

The module implements three types of queue, which differ only in the order inwhich the entries are retrieved. In aFIFOqueue, the first tasks added are the first retrieved. In aLIFO 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.

Internally, those three types of queues use locks to temporarily blockcompeting threads; however, they are not designed to handle reentrancywithin a thread.

In addition, the module implements a “simple”FIFO queue type,SimpleQueue, whosespecific implementation provides additional guaranteesin exchange for the smaller functionality.

Thequeue module defines the following classes and exceptions:

classqueue.Queue(maxsize=0)

Constructor for aFIFO queue.maxsize isan 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 aLIFO queue.maxsize isan 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.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).

If thedata elements are not comparable, the data can be wrapped in a classthat ignores the data item and only compares the priority number:

fromdataclassesimportdataclass,fieldfromtypingimportAny@dataclass(order=True)classPrioritizedItem:priority:intitem:Any=field(compare=False)
classqueue.SimpleQueue

Constructor for an unboundedFIFO queue.Simple queues lack advanced functionality such as task tracking.

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.

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=True,timeout=None)

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

Queue.put_nowait(item)

Equivalent toput(item,False).

Queue.get(block=True,timeout=None)

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

Prior to 3.0 on POSIX systems, and for all versions on Windows, ifblock is true andtimeout isNone, this operation goes intoan uninterruptible wait on an underlying lock. This means that no exceptionscan occur, and in particular a SIGINT will not trigger aKeyboardInterrupt.

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.

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.

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

importthreading,queueq=queue.Queue()defworker():whileTrue:item=q.get()print(f'Working on{item}')print(f'Finished{item}')q.task_done()# turn-on the worker threadthreading.Thread(target=worker,daemon=True).start()# send thirty task requests to the workerforiteminrange(30):q.put(item)print('All task requests sent\n',end='')# block until all tasks are doneq.join()print('All work completed')

SimpleQueue Objects

SimpleQueue objects provide the public methods described below.

SimpleQueue.qsize()

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

SimpleQueue.empty()

ReturnTrue if the queue is empty,False otherwise. If empty()returnsFalse it doesn’t guarantee that a subsequent call to get()will not block.

SimpleQueue.put(item,block=True,timeout=None)

Putitem into the queue. The method never blocks and always succeeds(except for potential low-level errors such as failure to allocate memory).The optional argsblock andtimeout are ignored and only providedfor compatibility withQueue.put().

CPython implementation detail: This method has a C implementation which is reentrant. That is, aput() orget() call can be interrupted by anotherput()call in the same thread without deadlocking or corrupting internalstate inside the queue. This makes it appropriate for use indestructors such as__del__ methods orweakref callbacks.

SimpleQueue.put_nowait(item)

Equivalent toput(item), provided for compatibility withQueue.put_nowait().

SimpleQueue.get(block=True,timeout=None)

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

SimpleQueue.get_nowait()

Equivalent toget(False).

See also

Classmultiprocessing.Queue

A queue class for use in a multi-processing (rather than multi-threading)context.

collections.deque is an alternative implementation of unboundedqueues with fast atomicappend() andpopleft() operations that do not require lockingand also support indexing.