Alexandre Vassalotti | f260e44 | 2008-05-11 19:59:59 +0000 | [diff] [blame] | 1 | :mod:`queue` --- A synchronized queue class |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2 | =========================================== |
| 3 | |
Alexandre Vassalotti | f260e44 | 2008-05-11 19:59:59 +0000 | [diff] [blame] | 4 | .. module:: queue |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 5 | :synopsis: A synchronized queue class. |
| 6 | |
Raymond Hettinger | 1048094 | 2011-01-10 03:26:08 +0000 | [diff] [blame] | 7 | **Source code:** :source:`Lib/queue.py` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 8 | |
Raymond Hettinger | 4f707fd | 2011-01-10 19:54:11 +0000 | [diff] [blame] | 9 | -------------- |
| 10 | |
Alexandre Vassalotti | f260e44 | 2008-05-11 19:59:59 +0000 | [diff] [blame] | 11 | The :mod:`queue` module implements multi-producer, multi-consumer queues. |
Thomas Wouters | 89d996e | 2007-09-08 17:39:28 +0000 | [diff] [blame] | 12 | It is especially useful in threaded programming when information must be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | exchanged safely between multiple threads. The :class:`Queue` class in this |
Zackery Spytz | eef0596 | 2018-09-29 10:07:11 -0600 | [diff] [blame] | 14 | module implements all the required locking semantics. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 15 | |
R David Murray | b98b37f | 2012-05-08 21:28:24 -0400 | [diff] [blame] | 16 | The module implements three types of queue, which differ only in the order in |
Serhiy Storchaka | 4ecfa45 | 2016-05-16 09:31:54 +0300 | [diff] [blame] | 17 | which the entries are retrieved. In a :abbr:`FIFO (first-in, first-out)` |
| 18 | queue, 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 Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 20 | the first retrieved (operating like a stack). With a priority queue, |
| 21 | the entries are kept sorted (using the :mod:`heapq` module) and the |
| 22 | lowest valued entry is retrieved first. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 23 | |
Antoine Pitrou | 94e1696 | 2018-01-16 00:27:16 +0100 | [diff] [blame] | 24 | Internally, those three types of queues use locks to temporarily block |
| 25 | competing threads; however, they are not designed to handle reentrancy |
| 26 | within a thread. |
| 27 | |
| 28 | In addition, the module implements a "simple" |
| 29 | :abbr:`FIFO (first-in, first-out)` queue type where |
| 30 | specific implementations can provide additional guarantees |
| 31 | in exchange for the smaller functionality. |
Éric Araujo | 6e6cb8e | 2010-11-16 19:13:50 +0000 | [diff] [blame] | 32 | |
Alexandre Vassalotti | f260e44 | 2008-05-11 19:59:59 +0000 | [diff] [blame] | 33 | The :mod:`queue` module defines the following classes and exceptions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 34 | |
Andrew M. Kuchling | 2b600e5 | 2010-02-26 13:35:56 +0000 | [diff] [blame] | 35 | .. class:: Queue(maxsize=0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | |
Serhiy Storchaka | 4ecfa45 | 2016-05-16 09:31:54 +0300 | [diff] [blame] | 37 | Constructor for a :abbr:`FIFO (first-in, first-out)` queue. *maxsize* is |
| 38 | an integer that sets the upperbound |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 39 | 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. Kuchling | 2b600e5 | 2010-02-26 13:35:56 +0000 | [diff] [blame] | 43 | .. class:: LifoQueue(maxsize=0) |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 44 | |
Serhiy Storchaka | 4ecfa45 | 2016-05-16 09:31:54 +0300 | [diff] [blame] | 45 | Constructor for a :abbr:`LIFO (last-in, first-out)` queue. *maxsize* is |
| 46 | an integer that sets the upperbound |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 47 | 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 Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 51 | |
Andrew M. Kuchling | 2b600e5 | 2010-02-26 13:35:56 +0000 | [diff] [blame] | 52 | .. class:: PriorityQueue(maxsize=0) |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 53 | |
| 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 62 | |
Raymond Hettinger | 0c3be96 | 2018-01-11 22:06:34 -0800 | [diff] [blame] | 63 | 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 Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 73 | |
Antoine Pitrou | 94e1696 | 2018-01-16 00:27:16 +0100 | [diff] [blame] | 74 | .. 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 82 | .. exception:: Empty |
| 83 | |
Serhiy Storchaka | 9e0ae53 | 2013-08-24 00:23:38 +0300 | [diff] [blame] | 84 | Exception raised when non-blocking :meth:`~Queue.get` (or |
| 85 | :meth:`~Queue.get_nowait`) is called |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 86 | on a :class:`Queue` object which is empty. |
| 87 | |
| 88 | |
| 89 | .. exception:: Full |
| 90 | |
Serhiy Storchaka | 9e0ae53 | 2013-08-24 00:23:38 +0300 | [diff] [blame] | 91 | Exception raised when non-blocking :meth:`~Queue.put` (or |
| 92 | :meth:`~Queue.put_nowait`) is called |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 93 | on a :class:`Queue` object which is full. |
| 94 | |
| 95 | |
| 96 | .. _queueobjects: |
| 97 | |
| 98 | Queue Objects |
| 99 | ------------- |
| 100 | |
Christian Heimes | 292d351 | 2008-02-03 16:51:08 +0000 | [diff] [blame] | 101 | Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 102 | provide the public methods described below. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 103 | |
| 104 | |
| 105 | .. method:: Queue.qsize() |
| 106 | |
Guido van Rossum | 7736b5b | 2008-01-15 21:44:53 +0000 | [diff] [blame] | 107 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 110 | |
| 111 | |
Raymond Hettinger | 47aa989 | 2009-03-07 14:07:37 +0000 | [diff] [blame] | 112 | .. 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 Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 128 | .. method:: Queue.put(item, block=True, timeout=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 129 | |
| 130 | Put *item* into the queue. If optional args *block* is true and *timeout* is |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 131 | ``None`` (the default), block if necessary until a free slot is available. If |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 132 | *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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 138 | |
| 139 | .. method:: Queue.put_nowait(item) |
| 140 | |
| 141 | Equivalent to ``put(item, False)``. |
| 142 | |
| 143 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 144 | .. method:: Queue.get(block=True, timeout=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 145 | |
| 146 | Remove and return an item from the queue. If optional args *block* is true and |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 147 | *timeout* is ``None`` (the default), block if necessary until an item is available. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 148 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 153 | |
| 154 | .. method:: Queue.get_nowait() |
| 155 | |
| 156 | Equivalent to ``get(False)``. |
| 157 | |
| 158 | Two methods are offered to support tracking whether enqueued tasks have been |
| 159 | fully 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 175 | |
| 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 Hettinger | 28c013d | 2009-03-10 00:07:25 +0000 | [diff] [blame] | 183 | count of unfinished tasks drops to zero, :meth:`join` unblocks. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 185 | |
| 186 | Example of how to wait for enqueued tasks to be completed:: |
| 187 | |
Victor Stinner | de31134 | 2015-03-18 14:05:43 +0100 | [diff] [blame] | 188 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 195 | |
Victor Stinner | de31134 | 2015-03-18 14:05:43 +0100 | [diff] [blame] | 196 | q = queue.Queue() |
| 197 | threads = [] |
| 198 | for i in range(num_worker_threads): |
| 199 | t = threading.Thread(target=worker) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 200 | t.start() |
Victor Stinner | de31134 | 2015-03-18 14:05:43 +0100 | [diff] [blame] | 201 | threads.append(t) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 202 | |
Victor Stinner | de31134 | 2015-03-18 14:05:43 +0100 | [diff] [blame] | 203 | for item in source(): |
| 204 | q.put(item) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 205 | |
Victor Stinner | de31134 | 2015-03-18 14:05:43 +0100 | [diff] [blame] | 206 | # 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 214 | |
Antoine Pitrou | 696efdd | 2011-01-07 19:16:12 +0000 | [diff] [blame] | 215 | |
Antoine Pitrou | 94e1696 | 2018-01-16 00:27:16 +0100 | [diff] [blame] | 216 | SimpleQueue 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 Pitrou | 696efdd | 2011-01-07 19:16:12 +0000 | [diff] [blame] | 270 | .. 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 Brandl | 2f2a9f7 | 2011-01-07 20:58:25 +0000 | [diff] [blame] | 276 | :class:`collections.deque` is an alternative implementation of unbounded |
Serhiy Storchaka | 9e0ae53 | 2013-08-24 00:23:38 +0300 | [diff] [blame] | 277 | queues with fast atomic :meth:`~collections.deque.append` and |
| 278 | :meth:`~collections.deque.popleft` operations that do not require locking. |