blob: 0a42da1d74a44ae4cf528fb721406d1c269edf19 [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"
Miss Islington (bot)76d31a32018-10-19 15:33:36 -070031:abbr:`FIFO (first-in, first-out)` queue type, :class:`SimpleQueue`, whose
32specific implementation provides additional guarantees
Antoine Pitrou94e16962018-01-16 00:27:16 +010033in 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
Miss Islington (bot)f3c55352019-03-25 13:03:16 -0700155 Prior to 3.0 on POSIX systems, and for all versions on Windows, if
156 *block* is true and *timeout* is ``None``, this operation goes into
157 an uninterruptible wait on an underlying lock. This means that no exceptions
158 can occur, and in particular a SIGINT will not trigger a :exc:`KeyboardInterrupt`.
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161.. method:: Queue.get_nowait()
162
163 Equivalent to ``get(False)``.
164
165Two methods are offered to support tracking whether enqueued tasks have been
166fully processed by daemon consumer threads.
167
168
169.. method:: Queue.task_done()
170
171 Indicate that a formerly enqueued task is complete. Used by queue consumer
172 threads. For each :meth:`get` used to fetch a task, a subsequent call to
173 :meth:`task_done` tells the queue that the processing on the task is complete.
174
175 If a :meth:`join` is currently blocking, it will resume when all items have been
176 processed (meaning that a :meth:`task_done` call was received for every item
177 that had been :meth:`put` into the queue).
178
179 Raises a :exc:`ValueError` if called more times than there were items placed in
180 the queue.
181
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183.. method:: Queue.join()
184
185 Blocks until all items in the queue have been gotten and processed.
186
187 The count of unfinished tasks goes up whenever an item is added to the queue.
188 The count goes down whenever a consumer thread calls :meth:`task_done` to
189 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000190 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193Example of how to wait for enqueued tasks to be completed::
194
Victor Stinnerde311342015-03-18 14:05:43 +0100195 def worker():
196 while True:
197 item = q.get()
198 if item is None:
199 break
200 do_work(item)
201 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Victor Stinnerde311342015-03-18 14:05:43 +0100203 q = queue.Queue()
204 threads = []
205 for i in range(num_worker_threads):
206 t = threading.Thread(target=worker)
Georg Brandl48310cd2009-01-03 21:18:54 +0000207 t.start()
Victor Stinnerde311342015-03-18 14:05:43 +0100208 threads.append(t)
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Victor Stinnerde311342015-03-18 14:05:43 +0100210 for item in source():
211 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Victor Stinnerde311342015-03-18 14:05:43 +0100213 # block until all tasks are done
214 q.join()
215
216 # stop workers
217 for i in range(num_worker_threads):
218 q.put(None)
219 for t in threads:
220 t.join()
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000222
Antoine Pitrou94e16962018-01-16 00:27:16 +0100223SimpleQueue Objects
224-------------------
225
226:class:`SimpleQueue` objects provide the public methods described below.
227
228.. method:: SimpleQueue.qsize()
229
230 Return the approximate size of the queue. Note, qsize() > 0 doesn't
231 guarantee that a subsequent get() will not block.
232
233
234.. method:: SimpleQueue.empty()
235
236 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
237 returns ``False`` it doesn't guarantee that a subsequent call to get()
238 will not block.
239
240
241.. method:: SimpleQueue.put(item, block=True, timeout=None)
242
243 Put *item* into the queue. The method never blocks and always succeeds
244 (except for potential low-level errors such as failure to allocate memory).
245 The optional args *block* and *timeout* are ignored and only provided
246 for compatibility with :meth:`Queue.put`.
247
248 .. impl-detail::
249 This method has a C implementation which is reentrant. That is, a
250 ``put()`` or ``get()`` call can be interrupted by another ``put()``
251 call in the same thread without deadlocking or corrupting internal
252 state inside the queue. This makes it appropriate for use in
253 destructors such as ``__del__`` methods or :mod:`weakref` callbacks.
254
255
256.. method:: SimpleQueue.put_nowait(item)
257
258 Equivalent to ``put(item)``, provided for compatibility with
259 :meth:`Queue.put_nowait`.
260
261
262.. method:: SimpleQueue.get(block=True, timeout=None)
263
264 Remove and return an item from the queue. If optional args *block* is true and
265 *timeout* is ``None`` (the default), block if necessary until an item is available.
266 If *timeout* is a positive number, it blocks at most *timeout* seconds and
267 raises the :exc:`Empty` exception if no item was available within that time.
268 Otherwise (*block* is false), return an item if one is immediately available,
269 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
270
271
272.. method:: SimpleQueue.get_nowait()
273
274 Equivalent to ``get(False)``.
275
276
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000277.. seealso::
278
279 Class :class:`multiprocessing.Queue`
280 A queue class for use in a multi-processing (rather than multi-threading)
281 context.
282
Georg Brandl2f2a9f72011-01-07 20:58:25 +0000283 :class:`collections.deque` is an alternative implementation of unbounded
Serhiy Storchaka9e0ae532013-08-24 00:23:38 +0300284 queues with fast atomic :meth:`~collections.deque.append` and
285 :meth:`~collections.deque.popleft` operations that do not require locking.