blob: 1520faa9b83ff03d0305dba491f34196ae9bd021 [file] [log] [blame]
Alexandre Vassalottif260e442008-05-11 19:59:59 +00001:mod:`queue` --- A synchronized queue class
Georg Brandl116aa622007-08-15 14:28:22 +00002===========================================
3
Alexandre Vassalottif260e442008-05-11 19:59:59 +00004.. module:: queue
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: A synchronized queue class.
6
Raymond Hettinger10480942011-01-10 03:26:08 +00007**Source code:** :source:`Lib/queue.py`
Georg Brandl116aa622007-08-15 14:28:22 +00008
Raymond Hettinger4f707fd2011-01-10 19:54:11 +00009--------------
10
Alexandre Vassalottif260e442008-05-11 19:59:59 +000011The :mod:`queue` module implements multi-producer, multi-consumer queues.
Thomas Wouters89d996e2007-09-08 17:39:28 +000012It is especially useful in threaded programming when information must be
Georg Brandl116aa622007-08-15 14:28:22 +000013exchanged safely between multiple threads. The :class:`Queue` class in this
14module implements all the required locking semantics. It depends on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000015availability of thread support in Python; see the :mod:`threading`
16module.
Georg Brandl116aa622007-08-15 14:28:22 +000017
R David Murrayb98b37f2012-05-08 21:28:24 -040018The module implements three types of queue, which differ only in the order in
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +030019which the entries are retrieved. In a :abbr:`FIFO (first-in, first-out)`
20queue, the first tasks added are the first retrieved. In a
21:abbr:`LIFO (last-in, first-out)` queue, the most recently added entry is
Raymond Hettinger35641462008-01-17 00:13:27 +000022the first retrieved (operating like a stack). With a priority queue,
23the entries are kept sorted (using the :mod:`heapq` module) and the
24lowest valued entry is retrieved first.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Antoine Pitrou94e16962018-01-16 00:27:16 +010026Internally, those three types of queues use locks to temporarily block
27competing threads; however, they are not designed to handle reentrancy
28within a thread.
29
30In addition, the module implements a "simple"
31:abbr:`FIFO (first-in, first-out)` queue type where
32specific implementations can provide additional guarantees
33in exchange for the smaller functionality.
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000034
Alexandre Vassalottif260e442008-05-11 19:59:59 +000035The :mod:`queue` module defines the following classes and exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +000036
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000037.. class:: Queue(maxsize=0)
Georg Brandl116aa622007-08-15 14:28:22 +000038
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +030039 Constructor for a :abbr:`FIFO (first-in, first-out)` queue. *maxsize* is
40 an integer that sets the upperbound
Georg Brandl116aa622007-08-15 14:28:22 +000041 limit on the number of items that can be placed in the queue. Insertion will
42 block once this size has been reached, until queue items are consumed. If
43 *maxsize* is less than or equal to zero, the queue size is infinite.
44
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000045.. class:: LifoQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000046
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +030047 Constructor for a :abbr:`LIFO (last-in, first-out)` queue. *maxsize* is
48 an integer that sets the upperbound
Raymond Hettinger35641462008-01-17 00:13:27 +000049 limit on the number of items that can be placed in the queue. Insertion will
50 block once this size has been reached, until queue items are consumed. If
51 *maxsize* is less than or equal to zero, the queue size is infinite.
52
Christian Heimes679db4a2008-01-18 09:56:22 +000053
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000054.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000055
56 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
57 limit on the number of items that can be placed in the queue. Insertion will
58 block once this size has been reached, until queue items are consumed. If
59 *maxsize* is less than or equal to zero, the queue size is infinite.
60
61 The lowest valued entries are retrieved first (the lowest valued entry is the
62 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
63 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl116aa622007-08-15 14:28:22 +000064
Raymond Hettinger0c3be962018-01-11 22:06:34 -080065 If the *data* elements are not comparable, the data can be wrapped in a class
66 that ignores the data item and only compares the priority number::
67
68 from dataclasses import dataclass, field
69 from typing import Any
70
71 @dataclass(order=True)
72 class PrioritizedItem:
73 priority: int
74 item: Any=field(compare=False)
Christian Heimes679db4a2008-01-18 09:56:22 +000075
Antoine Pitrou94e16962018-01-16 00:27:16 +010076.. class:: SimpleQueue()
77
78 Constructor for an unbounded :abbr:`FIFO (first-in, first-out)` queue.
79 Simple queues lack advanced functionality such as task tracking.
80
81 .. versionadded:: 3.7
82
83
Georg Brandl116aa622007-08-15 14:28:22 +000084.. exception:: Empty
85
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +030086 Exception raised when non-blocking :meth:`~Queue.get` (or
87 :meth:`~Queue.get_nowait`) is called
Georg Brandl116aa622007-08-15 14:28:22 +000088 on a :class:`Queue` object which is empty.
89
90
91.. exception:: Full
92
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +030093 Exception raised when non-blocking :meth:`~Queue.put` (or
94 :meth:`~Queue.put_nowait`) is called
Georg Brandl116aa622007-08-15 14:28:22 +000095 on a :class:`Queue` object which is full.
96
97
98.. _queueobjects:
99
100Queue Objects
101-------------
102
Christian Heimes292d3512008-02-03 16:51:08 +0000103Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandl48310cd2009-01-03 21:18:54 +0000104provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106
107.. method:: Queue.qsize()
108
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000109 Return the approximate size of the queue. Note, qsize() > 0 doesn't
110 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
111 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
Raymond Hettinger47aa9892009-03-07 14:07:37 +0000114.. method:: Queue.empty()
115
116 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
117 returns ``True`` it doesn't guarantee that a subsequent call to put()
118 will not block. Similarly, if empty() returns ``False`` it doesn't
119 guarantee that a subsequent call to get() will not block.
120
121
122.. method:: Queue.full()
123
124 Return ``True`` if the queue is full, ``False`` otherwise. If full()
125 returns ``True`` it doesn't guarantee that a subsequent call to get()
126 will not block. Similarly, if full() returns ``False`` it doesn't
127 guarantee that a subsequent call to put() will not block.
128
129
Georg Brandl18244152009-09-02 20:34:52 +0000130.. method:: Queue.put(item, block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132 Put *item* into the queue. If optional args *block* is true and *timeout* is
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300133 ``None`` (the default), block if necessary until a free slot is available. If
Georg Brandl116aa622007-08-15 14:28:22 +0000134 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
135 the :exc:`Full` exception if no free slot was available within that time.
136 Otherwise (*block* is false), put an item on the queue if a free slot is
137 immediately available, else raise the :exc:`Full` exception (*timeout* is
138 ignored in that case).
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141.. method:: Queue.put_nowait(item)
142
143 Equivalent to ``put(item, False)``.
144
145
Georg Brandl18244152009-09-02 20:34:52 +0000146.. method:: Queue.get(block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148 Remove and return an item from the queue. If optional args *block* is true and
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300149 *timeout* is ``None`` (the default), block if necessary until an item is available.
Georg Brandl116aa622007-08-15 14:28:22 +0000150 If *timeout* is a positive number, it blocks at most *timeout* seconds and
151 raises the :exc:`Empty` exception if no item was available within that time.
152 Otherwise (*block* is false), return an item if one is immediately available,
153 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
154
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156.. method:: Queue.get_nowait()
157
158 Equivalent to ``get(False)``.
159
160Two methods are offered to support tracking whether enqueued tasks have been
161fully processed by daemon consumer threads.
162
163
164.. method:: Queue.task_done()
165
166 Indicate that a formerly enqueued task is complete. Used by queue consumer
167 threads. For each :meth:`get` used to fetch a task, a subsequent call to
168 :meth:`task_done` tells the queue that the processing on the task is complete.
169
170 If a :meth:`join` is currently blocking, it will resume when all items have been
171 processed (meaning that a :meth:`task_done` call was received for every item
172 that had been :meth:`put` into the queue).
173
174 Raises a :exc:`ValueError` if called more times than there were items placed in
175 the queue.
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. method:: Queue.join()
179
180 Blocks until all items in the queue have been gotten and processed.
181
182 The count of unfinished tasks goes up whenever an item is added to the queue.
183 The count goes down whenever a consumer thread calls :meth:`task_done` to
184 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000185 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000186
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188Example of how to wait for enqueued tasks to be completed::
189
Victor Stinnerde311342015-03-18 14:05:43 +0100190 def worker():
191 while True:
192 item = q.get()
193 if item is None:
194 break
195 do_work(item)
196 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Victor Stinnerde311342015-03-18 14:05:43 +0100198 q = queue.Queue()
199 threads = []
200 for i in range(num_worker_threads):
201 t = threading.Thread(target=worker)
Georg Brandl48310cd2009-01-03 21:18:54 +0000202 t.start()
Victor Stinnerde311342015-03-18 14:05:43 +0100203 threads.append(t)
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Victor Stinnerde311342015-03-18 14:05:43 +0100205 for item in source():
206 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Victor Stinnerde311342015-03-18 14:05:43 +0100208 # block until all tasks are done
209 q.join()
210
211 # stop workers
212 for i in range(num_worker_threads):
213 q.put(None)
214 for t in threads:
215 t.join()
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000217
Antoine Pitrou94e16962018-01-16 00:27:16 +0100218SimpleQueue Objects
219-------------------
220
221:class:`SimpleQueue` objects provide the public methods described below.
222
223.. method:: SimpleQueue.qsize()
224
225 Return the approximate size of the queue. Note, qsize() > 0 doesn't
226 guarantee that a subsequent get() will not block.
227
228
229.. method:: SimpleQueue.empty()
230
231 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
232 returns ``False`` it doesn't guarantee that a subsequent call to get()
233 will not block.
234
235
236.. method:: SimpleQueue.put(item, block=True, timeout=None)
237
238 Put *item* into the queue. The method never blocks and always succeeds
239 (except for potential low-level errors such as failure to allocate memory).
240 The optional args *block* and *timeout* are ignored and only provided
241 for compatibility with :meth:`Queue.put`.
242
243 .. impl-detail::
244 This method has a C implementation which is reentrant. That is, a
245 ``put()`` or ``get()`` call can be interrupted by another ``put()``
246 call in the same thread without deadlocking or corrupting internal
247 state inside the queue. This makes it appropriate for use in
248 destructors such as ``__del__`` methods or :mod:`weakref` callbacks.
249
250
251.. method:: SimpleQueue.put_nowait(item)
252
253 Equivalent to ``put(item)``, provided for compatibility with
254 :meth:`Queue.put_nowait`.
255
256
257.. method:: SimpleQueue.get(block=True, timeout=None)
258
259 Remove and return an item from the queue. If optional args *block* is true and
260 *timeout* is ``None`` (the default), block if necessary until an item is available.
261 If *timeout* is a positive number, it blocks at most *timeout* seconds and
262 raises the :exc:`Empty` exception if no item was available within that time.
263 Otherwise (*block* is false), return an item if one is immediately available,
264 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
265
266
267.. method:: SimpleQueue.get_nowait()
268
269 Equivalent to ``get(False)``.
270
271
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000272.. seealso::
273
274 Class :class:`multiprocessing.Queue`
275 A queue class for use in a multi-processing (rather than multi-threading)
276 context.
277
Georg Brandl2f2a9f72011-01-07 20:58:25 +0000278 :class:`collections.deque` is an alternative implementation of unbounded
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +0300279 queues with fast atomic :meth:`~collections.deque.append` and
280 :meth:`~collections.deque.popleft` operations that do not require locking.