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 aQueue
object which is empty.
- exceptionqueue.Full¶
Exception raised when non-blocking
put()
(orput_nowait()
) is calledon aQueue
object which is full.
- exceptionqueue.ShutDown¶
Exception raised when
put()
orget()
is called onaQueue
object 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
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’tguarantee that a subsequent call to get() will not block.
- Queue.full()¶
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’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 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).Raises
ShutDown
if 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 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 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
ShutDown
if 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).shutdown(immediate=True)
callstask_done()
for each remaining itemin the queue.Raises a
ValueError
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 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.
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¶
Queue
objects can be made to prevent further interaction by shuttingthem down.
- Queue.shutdown(immediate=False)¶
Shut down the queue, making
get()
andput()
raiseShutDown
.By default,
get()
on a shut down queue will only raise once thequeue is empty. Setimmediate to true to makeget()
raiseimmediately instead.All blocked callers of
put()
andget()
will beunblocked. Ifimmediate is true, a task will be marked as done for eachremaining item in the queue, which may unblock callers ofjoin()
.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
True
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 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 orweakref
callbacks.
- 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 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 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.