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)¶
- classqueue.LifoQueue(maxsize=0)¶
- 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 that would be returned by
min(entries)). A typical pattern forentries is 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.
Added in version 3.7.
- exceptionqueue.Empty¶
Exception raised when non-blocking
get()(orget_nowait()) is calledon aQueueobject which is empty.
- exceptionqueue.Full¶
Exception raised when non-blocking
put()(orput_nowait()) is calledon aQueueobject which is full.
- exceptionqueue.ShutDown¶
Exception raised when
put()orget()is called onaQueueobject which has been shut down.Added in version 3.13.
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()¶
Return
Trueif the queue is empty,Falseotherwise. If empty()returnsTrueit doesn’t guarantee that a subsequent call to put()will not block. Similarly, if empty() returnsFalseit doesn’tguarantee that a subsequent call to get() will not block.
- Queue.full()¶
Return
Trueif the queue is full,Falseotherwise. If full()returnsTrueit doesn’t guarantee that a subsequent call to get()will not block. Similarly, if full() returnsFalseit 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 is
None(the default), block if necessary until a free slot is available. Iftimeout is a positive number, it blocks at mosttimeout seconds and raisestheFullexception 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 theFullexception (timeout isignored in that case).Raises
ShutDownif the queue has been shut down.
- Queue.put_nowait(item)¶
Equivalent to
put(item,block=False).
- Queue.get(block=True,timeout=None)¶
Remove and return an item from the queue. If optional argsblock is true andtimeout is
None(the default), block if necessary until an item is available.Iftimeout is a positive number, it blocks at mosttimeout seconds andraises theEmptyexception if no item was available within that time.Otherwise (block is false), return an item if one is immediately available,else raise theEmptyexception (timeout is ignored in that case).Prior to 3.0 on POSIX systems, and for all versions on Windows, ifblock is true andtimeout is
None, 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.Raises
ShutDownif the queue has been shut down and is empty, or ifthe queue has been shut down immediately.
- Queue.get_nowait()¶
Equivalent to
get(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 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 beenprocessed (meaning that atask_done()call was received for every itemthat had beenput()into the queue).Raises a
ValueErrorif 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 calls
task_done()toindicate that the item was retrieved and all work on it is complete. When thecount of unfinished tasks drops to zero,join()unblocks.
Waiting for task completion¶
Example of how to wait for enqueued tasks to be completed:
importthreadingimportqueueq=queue.Queue()defworker():whileTrue:item=q.get()print(f'Working on{item}')print(f'Finished{item}')q.task_done()# Turn-on the worker thread.threading.Thread(target=worker,daemon=True).start()# Send thirty task requests to the worker.foriteminrange(30):q.put(item)# Block until all tasks are done.q.join()print('All work completed')
Terminating queues¶
When no longer needed,Queue objects can be wound downuntil empty or terminated immediately with a hard shutdown.
- Queue.shutdown(immediate=False)¶
Put a
Queueinstance into a shutdown mode.The queue can no longer grow.Future calls to
put()raiseShutDown.Currently blocked callers ofput()will be unblockedand will raiseShutDownin the formerly blocked thread.Ifimmediate is false (the default), the queue can be wounddown normally with
get()calls to extract tasksthat have already been loaded.And if
task_done()is called for each remaining task, apendingjoin()will be unblocked normally.Once the queue is empty, future calls to
get()willraiseShutDown.Ifimmediate is true, the queue is terminated immediately.The queue is drained to be completely empty and the countof unfinished tasks is reduced by the number of tasks drained.If unfinished tasks is zero, callers of
join()are unblocked. Also, blocked callers ofget()are unblocked and will raiseShutDownbecause thequeue is empty.Use caution when using
join()withimmediate setto true. This unblocks the join even when no work has been doneon the tasks, violating the usual invariant for joining a queue.Added in version 3.13.
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()¶
Return
Trueif the queue is empty,Falseotherwise. If empty()returnsFalseit 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 with
Queue.put().CPython implementation detail: This method has a C implementation which is reentrant. That is, a
put()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 orweakrefcallbacks.
- SimpleQueue.put_nowait(item)¶
Equivalent to
put(item,block=False), 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 is
None(the default), block if necessary until an item is available.Iftimeout is a positive number, it blocks at mosttimeout seconds andraises theEmptyexception if no item was available within that time.Otherwise (block is false), return an item if one is immediately available,else raise theEmptyexception (timeout is ignored in that case).
- SimpleQueue.get_nowait()¶
Equivalent to
get(False).
See also
- Class
multiprocessing.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.