1
:mod:`Queue` --- A synchronized queue class
2
===========================================
5
:synopsis: A synchronized queue class.
8
The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3. The
9
:term:`2to3` tool will automatically adapt imports when converting your
12
**Source code:** :source:`Lib/Queue.py`
16
The :mod:`Queue` module implements multi-producer, multi-consumer queues.
17
It is especially useful in threaded programming when information must be
18
exchanged safely between multiple threads. The :class:`Queue` class in this
19
module implements all the required locking semantics. It depends on the
20
availability of thread support in Python; see the :mod:`threading`
23
The module implements three types of queue, which differ only in the order in
24
which the entries are retrieved. In a FIFO queue, the first tasks added are
25
the first retrieved. In a LIFO queue, the most recently added entry is
26
the first retrieved (operating like a stack). With a priority queue,
27
the entries are kept sorted (using the :mod:`heapq` module) and the
28
lowest valued entry is retrieved first.
30
The :mod:`Queue` module defines the following classes and exceptions:
32
.. class:: Queue(maxsize=0)
34
Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
35
limit on the number of items that can be placed in the queue. Insertion will
36
block once this size has been reached, until queue items are consumed. If
37
*maxsize* is less than or equal to zero, the queue size is infinite.
39
.. class:: LifoQueue(maxsize=0)
41
Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
42
limit on the number of items that can be placed in the queue. Insertion will
43
block once this size has been reached, until queue items are consumed. If
44
*maxsize* is less than or equal to zero, the queue size is infinite.
48
.. class:: PriorityQueue(maxsize=0)
50
Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
51
limit on the number of items that can be placed in the queue. Insertion will
52
block once this size has been reached, until queue items are consumed. If
53
*maxsize* is less than or equal to zero, the queue size is infinite.
55
The lowest valued entries are retrieved first (the lowest valued entry is the
56
one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
57
is a tuple in the form: ``(priority_number, data)``.
63
Exception raised when non-blocking :meth:`~Queue.get` (or
64
:meth:`~Queue.get_nowait`) is called
65
on a :class:`Queue` object which is empty.
70
Exception raised when non-blocking :meth:`~Queue.put` (or
71
:meth:`~Queue.put_nowait`) is called
72
on a :class:`Queue` object which is full.
76
:class:`collections.deque` is an alternative implementation of unbounded
77
queues with fast atomic :func:`append` and :func:`popleft` operations that
78
do not require locking.
86
Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
87
provide the public methods described below.
90
.. method:: Queue.qsize()
92
Return the approximate size of the queue. Note, qsize() > 0 doesn't
93
guarantee that a subsequent get() will not block, nor will qsize() < maxsize
94
guarantee that put() will not block.
97
.. method:: Queue.empty()
99
Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
100
returns ``True`` it doesn't guarantee that a subsequent call to put()
101
will not block. Similarly, if empty() returns ``False`` it doesn't
102
guarantee that a subsequent call to get() will not block.
105
.. method:: Queue.full()
107
Return ``True`` if the queue is full, ``False`` otherwise. If full()
108
returns ``True`` it doesn't guarantee that a subsequent call to get()
109
will not block. Similarly, if full() returns ``False`` it doesn't
110
guarantee that a subsequent call to put() will not block.
113
.. method:: Queue.put(item[, block[, timeout]])
115
Put *item* into the queue. If optional args *block* is true and *timeout* is
116
``None`` (the default), block if necessary until a free slot is available. If
117
*timeout* is a positive number, it blocks at most *timeout* seconds and raises
118
the :exc:`Full` exception if no free slot was available within that time.
119
Otherwise (*block* is false), put an item on the queue if a free slot is
120
immediately available, else raise the :exc:`Full` exception (*timeout* is
121
ignored in that case).
123
.. versionadded:: 2.3
124
The *timeout* parameter.
127
.. method:: Queue.put_nowait(item)
129
Equivalent to ``put(item, False)``.
132
.. method:: Queue.get([block[, timeout]])
134
Remove and return an item from the queue. If optional args *block* is true and
135
*timeout* is ``None`` (the default), block if necessary until an item is available.
136
If *timeout* is a positive number, it blocks at most *timeout* seconds and
137
raises the :exc:`Empty` exception if no item was available within that time.
138
Otherwise (*block* is false), return an item if one is immediately available,
139
else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
141
.. versionadded:: 2.3
142
The *timeout* parameter.
145
.. method:: Queue.get_nowait()
147
Equivalent to ``get(False)``.
149
Two methods are offered to support tracking whether enqueued tasks have been
150
fully processed by daemon consumer threads.
153
.. method:: Queue.task_done()
155
Indicate that a formerly enqueued task is complete. Used by queue consumer
156
threads. For each :meth:`get` used to fetch a task, a subsequent call to
157
:meth:`task_done` tells the queue that the processing on the task is complete.
159
If a :meth:`join` is currently blocking, it will resume when all items have been
160
processed (meaning that a :meth:`task_done` call was received for every item
161
that had been :meth:`put` into the queue).
163
Raises a :exc:`ValueError` if called more times than there were items placed in
166
.. versionadded:: 2.5
169
.. method:: Queue.join()
171
Blocks until all items in the queue have been gotten and processed.
173
The count of unfinished tasks goes up whenever an item is added to the queue.
174
The count goes down whenever a consumer thread calls :meth:`task_done` to
175
indicate that the item was retrieved and all work on it is complete. When the
176
count of unfinished tasks drops to zero, :meth:`join` unblocks.
178
.. versionadded:: 2.5
180
Example of how to wait for enqueued tasks to be completed::
189
for i in range(num_worker_threads):
190
t = Thread(target=worker)
194
for item in source():
197
q.join() # block until all tasks are done