blob: a471bb09a1711aa6078dc55ae79a2e2ecac65c0c [file] [log] [blame]
Georg Brandl7a148c22008-05-12 10:03:16 +00001:mod:`queue` --- A synchronized queue class
Georg Brandl8ec7f652007-08-15 14:28:01 +00002===========================================
3
4.. module:: Queue
5 :synopsis: A synchronized queue class.
6
Alexandre Vassalotti73812bf2008-05-11 20:04:03 +00007.. note::
Georg Brandla6168f92008-05-25 07:20:14 +00008 The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3.0. The
9 :term:`2to3` tool will automatically adapt imports when converting your
10 sources to 3.0.
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
Georg Brandl7a148c22008-05-12 10:03:16 +000012
Georg Brandla6168f92008-05-25 07:20:14 +000013The :mod:`Queue` module implements multi-producer, multi-consumer queues.
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000014It is especially useful in threaded programming when information must be
Georg Brandl8ec7f652007-08-15 14:28:01 +000015exchanged safely between multiple threads. The :class:`Queue` class in this
16module implements all the required locking semantics. It depends on the
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000017availability of thread support in Python; see the :mod:`threading`
18module.
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
Raymond Hettinger171f3912008-01-16 23:38:16 +000020Implements three types of queue whose only difference is the order that
21the entries are retrieved. In a FIFO queue, the first tasks added are
22the first retrieved. In a LIFO queue, the most recently added entry is
23the first retrieved (operating like a stack). With a priority queue,
24the entries are kept sorted (using the :mod:`heapq` module) and the
25lowest valued entry is retrieved first.
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
Raymond Hettingere679a372010-11-05 23:58:42 +000027.. seealso::
28
29 Latest version of the `queue module Python source code
Georg Brandl54d39212010-12-09 12:13:38 +000030 <http://svn.python.org/view/python/branches/release27-maint/Lib/Queue.py?view=markup>`_.
Raymond Hettingere679a372010-11-05 23:58:42 +000031
Georg Brandla6168f92008-05-25 07:20:14 +000032The :mod:`Queue` module defines the following classes and exceptions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000033
Andrew M. Kuchling9aeeffa2010-02-26 13:22:50 +000034.. class:: Queue(maxsize=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +000035
Raymond Hettinger171f3912008-01-16 23:38:16 +000036 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl8ec7f652007-08-15 14:28:01 +000037 limit on the number of items that can be placed in the queue. Insertion will
38 block once this size has been reached, until queue items are consumed. If
39 *maxsize* is less than or equal to zero, the queue size is infinite.
40
Andrew M. Kuchling9aeeffa2010-02-26 13:22:50 +000041.. class:: LifoQueue(maxsize=0)
Raymond Hettinger171f3912008-01-16 23:38:16 +000042
43 Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
44 limit on the number of items that can be placed in the queue. Insertion will
45 block once this size has been reached, until queue items are consumed. If
46 *maxsize* is less than or equal to zero, the queue size is infinite.
47
Raymond Hettingerd59f4572008-01-17 08:07:05 +000048 .. versionadded:: 2.6
49
Andrew M. Kuchling9aeeffa2010-02-26 13:22:50 +000050.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger171f3912008-01-16 23:38:16 +000051
52 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
53 limit on the number of items that can be placed in the queue. Insertion will
54 block once this size has been reached, until queue items are consumed. If
55 *maxsize* is less than or equal to zero, the queue size is infinite.
56
57 The lowest valued entries are retrieved first (the lowest valued entry is the
58 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
59 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000060
Raymond Hettingerd59f4572008-01-17 08:07:05 +000061 .. versionadded:: 2.6
62
Georg Brandl8ec7f652007-08-15 14:28:01 +000063.. exception:: Empty
64
65 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
66 on a :class:`Queue` object which is empty.
67
68
69.. exception:: Full
70
71 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
72 on a :class:`Queue` object which is full.
73
Raymond Hettinger9324ed82009-03-09 12:56:23 +000074.. seealso::
75
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.
79
Georg Brandl8ec7f652007-08-15 14:28:01 +000080
81.. _queueobjects:
82
83Queue Objects
84-------------
85
Brett Cannon89dfbe32008-02-03 02:34:14 +000086Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandla6168f92008-05-25 07:20:14 +000087provide the public methods described below.
Georg Brandl8ec7f652007-08-15 14:28:01 +000088
89
90.. method:: Queue.qsize()
91
Raymond Hettinger907cda62008-01-15 05:46:43 +000092 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
Skip Montanarof233b0c2008-01-15 03:40:20 +000094 guarantee that put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96
97.. method:: Queue.empty()
98
Skip Montanarof233b0c2008-01-15 03:40:20 +000099 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
104
105.. method:: Queue.full()
106
Skip Montanarof233b0c2008-01-15 03:40:20 +0000107 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.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000111
112
113.. method:: Queue.put(item[, block[, timeout]])
114
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).
122
123 .. versionadded:: 2.3
124 The *timeout* parameter.
125
126
127.. method:: Queue.put_nowait(item)
128
129 Equivalent to ``put(item, False)``.
130
131
132.. method:: Queue.get([block[, timeout]])
133
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).
140
141 .. versionadded:: 2.3
142 The *timeout* parameter.
143
144
145.. method:: Queue.get_nowait()
146
147 Equivalent to ``get(False)``.
148
149Two methods are offered to support tracking whether enqueued tasks have been
150fully processed by daemon consumer threads.
151
152
153.. method:: Queue.task_done()
154
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.
158
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).
162
163 Raises a :exc:`ValueError` if called more times than there were items placed in
164 the queue.
165
166 .. versionadded:: 2.5
167
168
169.. method:: Queue.join()
170
171 Blocks until all items in the queue have been gotten and processed.
172
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
Raymond Hettingerf4ea9292009-03-10 00:06:05 +0000176 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
178 .. versionadded:: 2.5
179
180Example of how to wait for enqueued tasks to be completed::
181
Georg Brandla6168f92008-05-25 07:20:14 +0000182 def worker():
183 while True:
184 item = q.get()
185 do_work(item)
186 q.task_done()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000187
Georg Brandla6168f92008-05-25 07:20:14 +0000188 q = Queue()
189 for i in range(num_worker_threads):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000190 t = Thread(target=worker)
Benjamin Petersone047d792009-10-20 03:14:10 +0000191 t.daemon = True
Georg Brandla6168f92008-05-25 07:20:14 +0000192 t.start()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
194 for item in source():
Georg Brandla6168f92008-05-25 07:20:14 +0000195 q.put(item)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000196
197 q.join() # block until all tasks are done
198