blob: 1fea86bfc5cd891c8a4b3cae7cc78924a0ae3cdd [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
Zackery Spytzeef05962018-09-29 10:07:11 -060014module implements all the required locking semantics.
Georg Brandl116aa622007-08-15 14:28:22 +000015
R David Murrayb98b37f2012-05-08 21:28:24 -040016The module implements three types of queue, which differ only in the order in
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +030017which the entries are retrieved. In a :abbr:`FIFO (first-in, first-out)`
18queue, the first tasks added are the first retrieved. In a
19:abbr:`LIFO (last-in, first-out)` queue, the most recently added entry is
Raymond Hettinger35641462008-01-17 00:13:27 +000020the first retrieved (operating like a stack). With a priority queue,
21the entries are kept sorted (using the :mod:`heapq` module) and the
22lowest valued entry is retrieved first.
Georg Brandl116aa622007-08-15 14:28:22 +000023
Antoine Pitrou94e16962018-01-16 00:27:16 +010024Internally, those three types of queues use locks to temporarily block
25competing threads; however, they are not designed to handle reentrancy
26within a thread.
27
28In addition, the module implements a "simple"
Julien Palardacef6902018-10-20 00:27:49 +020029:abbr:`FIFO (first-in, first-out)` queue type, :class:`SimpleQueue`, whose
30specific implementation provides additional guarantees
Antoine Pitrou94e16962018-01-16 00:27:16 +010031in exchange for the smaller functionality.
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000032
Alexandre Vassalottif260e442008-05-11 19:59:59 +000033The :mod:`queue` module defines the following classes and exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +000034
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000035.. class:: Queue(maxsize=0)
Georg Brandl116aa622007-08-15 14:28:22 +000036
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +030037 Constructor for a :abbr:`FIFO (first-in, first-out)` queue. *maxsize* is
38 an integer that sets the upperbound
Georg Brandl116aa622007-08-15 14:28:22 +000039 limit on the number of items that can be placed in the queue. Insertion will
40 block once this size has been reached, until queue items are consumed. If
41 *maxsize* is less than or equal to zero, the queue size is infinite.
42
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000043.. class:: LifoQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000044
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +030045 Constructor for a :abbr:`LIFO (last-in, first-out)` queue. *maxsize* is
46 an integer that sets the upperbound
Raymond Hettinger35641462008-01-17 00:13:27 +000047 limit on the number of items that can be placed in the queue. Insertion will
48 block once this size has been reached, until queue items are consumed. If
49 *maxsize* is less than or equal to zero, the queue size is infinite.
50
Christian Heimes679db4a2008-01-18 09:56:22 +000051
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000052.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000053
54 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
55 limit on the number of items that can be placed in the queue. Insertion will
56 block once this size has been reached, until queue items are consumed. If
57 *maxsize* is less than or equal to zero, the queue size is infinite.
58
59 The lowest valued entries are retrieved first (the lowest valued entry is the
60 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
61 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl116aa622007-08-15 14:28:22 +000062
Raymond Hettinger0c3be962018-01-11 22:06:34 -080063 If the *data* elements are not comparable, the data can be wrapped in a class
64 that ignores the data item and only compares the priority number::
65
66 from dataclasses import dataclass, field
67 from typing import Any
68
69 @dataclass(order=True)
70 class PrioritizedItem:
71 priority: int
72 item: Any=field(compare=False)
Christian Heimes679db4a2008-01-18 09:56:22 +000073
Antoine Pitrou94e16962018-01-16 00:27:16 +010074.. class:: SimpleQueue()
75
76 Constructor for an unbounded :abbr:`FIFO (first-in, first-out)` queue.
77 Simple queues lack advanced functionality such as task tracking.
78
79 .. versionadded:: 3.7
80
81
Georg Brandl116aa622007-08-15 14:28:22 +000082.. exception:: Empty
83
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +030084 Exception raised when non-blocking :meth:`~Queue.get` (or
85 :meth:`~Queue.get_nowait`) is called
Georg Brandl116aa622007-08-15 14:28:22 +000086 on a :class:`Queue` object which is empty.
87
88
89.. exception:: Full
90
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +030091 Exception raised when non-blocking :meth:`~Queue.put` (or
92 :meth:`~Queue.put_nowait`) is called
Georg Brandl116aa622007-08-15 14:28:22 +000093 on a :class:`Queue` object which is full.
94
95
96.. _queueobjects:
97
98Queue Objects
99-------------
100
Christian Heimes292d3512008-02-03 16:51:08 +0000101Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandl48310cd2009-01-03 21:18:54 +0000102provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104
105.. method:: Queue.qsize()
106
Guido van Rossum7736b5b2008-01-15 21:44:53 +0000107 Return the approximate size of the queue. Note, qsize() > 0 doesn't
108 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
109 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111
Raymond Hettinger47aa9892009-03-07 14:07:37 +0000112.. method:: Queue.empty()
113
114 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
115 returns ``True`` it doesn't guarantee that a subsequent call to put()
116 will not block. Similarly, if empty() returns ``False`` it doesn't
117 guarantee that a subsequent call to get() will not block.
118
119
120.. method:: Queue.full()
121
122 Return ``True`` if the queue is full, ``False`` otherwise. If full()
123 returns ``True`` it doesn't guarantee that a subsequent call to get()
124 will not block. Similarly, if full() returns ``False`` it doesn't
125 guarantee that a subsequent call to put() will not block.
126
127
Georg Brandl18244152009-09-02 20:34:52 +0000128.. method:: Queue.put(item, block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130 Put *item* into the queue. If optional args *block* is true and *timeout* is
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300131 ``None`` (the default), block if necessary until a free slot is available. If
Georg Brandl116aa622007-08-15 14:28:22 +0000132 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
133 the :exc:`Full` exception if no free slot was available within that time.
134 Otherwise (*block* is false), put an item on the queue if a free slot is
135 immediately available, else raise the :exc:`Full` exception (*timeout* is
136 ignored in that case).
137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139.. method:: Queue.put_nowait(item)
140
141 Equivalent to ``put(item, False)``.
142
143
Georg Brandl18244152009-09-02 20:34:52 +0000144.. method:: Queue.get(block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 Remove and return an item from the queue. If optional args *block* is true and
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300147 *timeout* is ``None`` (the default), block if necessary until an item is available.
Georg Brandl116aa622007-08-15 14:28:22 +0000148 If *timeout* is a positive number, it blocks at most *timeout* seconds and
149 raises the :exc:`Empty` exception if no item was available within that time.
150 Otherwise (*block* is false), return an item if one is immediately available,
151 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
152
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154.. method:: Queue.get_nowait()
155
156 Equivalent to ``get(False)``.
157
158Two methods are offered to support tracking whether enqueued tasks have been
159fully processed by daemon consumer threads.
160
161
162.. method:: Queue.task_done()
163
164 Indicate that a formerly enqueued task is complete. Used by queue consumer
165 threads. For each :meth:`get` used to fetch a task, a subsequent call to
166 :meth:`task_done` tells the queue that the processing on the task is complete.
167
168 If a :meth:`join` is currently blocking, it will resume when all items have been
169 processed (meaning that a :meth:`task_done` call was received for every item
170 that had been :meth:`put` into the queue).
171
172 Raises a :exc:`ValueError` if called more times than there were items placed in
173 the queue.
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176.. method:: Queue.join()
177
178 Blocks until all items in the queue have been gotten and processed.
179
180 The count of unfinished tasks goes up whenever an item is added to the queue.
181 The count goes down whenever a consumer thread calls :meth:`task_done` to
182 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000183 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Georg Brandl116aa622007-08-15 14:28:22 +0000185
186Example of how to wait for enqueued tasks to be completed::
187
Victor Stinnerde311342015-03-18 14:05:43 +0100188 def worker():
189 while True:
190 item = q.get()
191 if item is None:
192 break
193 do_work(item)
194 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000195
Victor Stinnerde311342015-03-18 14:05:43 +0100196 q = queue.Queue()
197 threads = []
198 for i in range(num_worker_threads):
199 t = threading.Thread(target=worker)
Georg Brandl48310cd2009-01-03 21:18:54 +0000200 t.start()
Victor Stinnerde311342015-03-18 14:05:43 +0100201 threads.append(t)
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Victor Stinnerde311342015-03-18 14:05:43 +0100203 for item in source():
204 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Victor Stinnerde311342015-03-18 14:05:43 +0100206 # block until all tasks are done
207 q.join()
208
209 # stop workers
210 for i in range(num_worker_threads):
211 q.put(None)
212 for t in threads:
213 t.join()
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000215
Antoine Pitrou94e16962018-01-16 00:27:16 +0100216SimpleQueue Objects
217-------------------
218
219:class:`SimpleQueue` objects provide the public methods described below.
220
221.. method:: SimpleQueue.qsize()
222
223 Return the approximate size of the queue. Note, qsize() > 0 doesn't
224 guarantee that a subsequent get() will not block.
225
226
227.. method:: SimpleQueue.empty()
228
229 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
230 returns ``False`` it doesn't guarantee that a subsequent call to get()
231 will not block.
232
233
234.. method:: SimpleQueue.put(item, block=True, timeout=None)
235
236 Put *item* into the queue. The method never blocks and always succeeds
237 (except for potential low-level errors such as failure to allocate memory).
238 The optional args *block* and *timeout* are ignored and only provided
239 for compatibility with :meth:`Queue.put`.
240
241 .. impl-detail::
242 This method has a C implementation which is reentrant. That is, a
243 ``put()`` or ``get()`` call can be interrupted by another ``put()``
244 call in the same thread without deadlocking or corrupting internal
245 state inside the queue. This makes it appropriate for use in
246 destructors such as ``__del__`` methods or :mod:`weakref` callbacks.
247
248
249.. method:: SimpleQueue.put_nowait(item)
250
251 Equivalent to ``put(item)``, provided for compatibility with
252 :meth:`Queue.put_nowait`.
253
254
255.. method:: SimpleQueue.get(block=True, timeout=None)
256
257 Remove and return an item from the queue. If optional args *block* is true and
258 *timeout* is ``None`` (the default), block if necessary until an item is available.
259 If *timeout* is a positive number, it blocks at most *timeout* seconds and
260 raises the :exc:`Empty` exception if no item was available within that time.
261 Otherwise (*block* is false), return an item if one is immediately available,
262 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
263
264
265.. method:: SimpleQueue.get_nowait()
266
267 Equivalent to ``get(False)``.
268
269
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000270.. seealso::
271
272 Class :class:`multiprocessing.Queue`
273 A queue class for use in a multi-processing (rather than multi-threading)
274 context.
275
Georg Brandl2f2a9f72011-01-07 20:58:25 +0000276 :class:`collections.deque` is an alternative implementation of unbounded
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +0300277 queues with fast atomic :meth:`~collections.deque.append` and
278 :meth:`~collections.deque.popleft` operations that do not require locking.