blob: ceede527e4613248d82602c6a166b96628e409c3 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`Queue` --- A synchronized queue class
3===========================================
4
5.. module:: Queue
6 :synopsis: A synchronized queue class.
7
Alexandre Vassalotti73812bf2008-05-11 20:04:03 +00008.. note::
9 The :mod:`Queue` module has been renamed to `queue` in Python 3.0.
Georg Brandl8ec7f652007-08-15 14:28:01 +000010
Raymond Hettinger171f3912008-01-16 23:38:16 +000011The :mod:`Queue` module implements multi-producer, multi-consumer queues.
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000012It is especially useful in threaded programming when information must be
Georg Brandl8ec7f652007-08-15 14:28:01 +000013exchanged safely between multiple threads. The :class:`Queue` class in this
14module implements all the required locking semantics. It depends on the
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000015availability of thread support in Python; see the :mod:`threading`
16module.
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
Raymond Hettinger171f3912008-01-16 23:38:16 +000018Implements three types of queue whose only difference is the order that
19the entries are retrieved. In a FIFO queue, the first tasks added are
20the first retrieved. In a LIFO queue, the most recently added entry is
21the first retrieved (operating like a stack). With a priority queue,
22the entries are kept sorted (using the :mod:`heapq` module) and the
23lowest valued entry is retrieved first.
Georg Brandl8ec7f652007-08-15 14:28:01 +000024
Raymond Hettinger171f3912008-01-16 23:38:16 +000025The :mod:`Queue` module defines the following classes and exceptions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
27.. class:: Queue(maxsize)
28
Raymond Hettinger171f3912008-01-16 23:38:16 +000029 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl8ec7f652007-08-15 14:28:01 +000030 limit on the number of items that can be placed in the queue. Insertion will
31 block once this size has been reached, until queue items are consumed. If
32 *maxsize* is less than or equal to zero, the queue size is infinite.
33
Raymond Hettinger171f3912008-01-16 23:38:16 +000034.. class:: LifoQueue(maxsize)
35
36 Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
37 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
Raymond Hettingerd59f4572008-01-17 08:07:05 +000041 .. versionadded:: 2.6
42
Raymond Hettinger171f3912008-01-16 23:38:16 +000043.. class:: PriorityQueue(maxsize)
44
45 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
46 limit on the number of items that can be placed in the queue. Insertion will
47 block once this size has been reached, until queue items are consumed. If
48 *maxsize* is less than or equal to zero, the queue size is infinite.
49
50 The lowest valued entries are retrieved first (the lowest valued entry is the
51 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
52 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
Raymond Hettingerd59f4572008-01-17 08:07:05 +000054 .. versionadded:: 2.6
55
Georg Brandl8ec7f652007-08-15 14:28:01 +000056.. exception:: Empty
57
58 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
59 on a :class:`Queue` object which is empty.
60
61
62.. exception:: Full
63
64 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
65 on a :class:`Queue` object which is full.
66
67
68.. _queueobjects:
69
70Queue Objects
71-------------
72
Brett Cannon89dfbe32008-02-03 02:34:14 +000073Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Raymond Hettinger171f3912008-01-16 23:38:16 +000074provide the public methods described below.
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
76
77.. method:: Queue.qsize()
78
Raymond Hettinger907cda62008-01-15 05:46:43 +000079 Return the approximate size of the queue. Note, qsize() > 0 doesn't
80 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
Skip Montanarof233b0c2008-01-15 03:40:20 +000081 guarantee that put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000082
83
84.. method:: Queue.empty()
85
Skip Montanarof233b0c2008-01-15 03:40:20 +000086 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
87 returns ``True`` it doesn't guarantee that a subsequent call to put()
88 will not block. Similarly, if empty() returns ``False`` it doesn't
89 guarantee that a subsequent call to get() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000090
91
92.. method:: Queue.full()
93
Skip Montanarof233b0c2008-01-15 03:40:20 +000094 Return ``True`` if the queue is full, ``False`` otherwise. If full()
95 returns ``True`` it doesn't guarantee that a subsequent call to get()
96 will not block. Similarly, if full() returns ``False`` it doesn't
97 guarantee that a subsequent call to put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000098
99
100.. method:: Queue.put(item[, block[, timeout]])
101
102 Put *item* into the queue. If optional args *block* is true and *timeout* is
103 None (the default), block if necessary until a free slot is available. If
104 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
105 the :exc:`Full` exception if no free slot was available within that time.
106 Otherwise (*block* is false), put an item on the queue if a free slot is
107 immediately available, else raise the :exc:`Full` exception (*timeout* is
108 ignored in that case).
109
110 .. versionadded:: 2.3
111 The *timeout* parameter.
112
113
114.. method:: Queue.put_nowait(item)
115
116 Equivalent to ``put(item, False)``.
117
118
119.. method:: Queue.get([block[, timeout]])
120
121 Remove and return an item from the queue. If optional args *block* is true and
122 *timeout* is None (the default), block if necessary until an item is available.
123 If *timeout* is a positive number, it blocks at most *timeout* seconds and
124 raises the :exc:`Empty` exception if no item was available within that time.
125 Otherwise (*block* is false), return an item if one is immediately available,
126 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
127
128 .. versionadded:: 2.3
129 The *timeout* parameter.
130
131
132.. method:: Queue.get_nowait()
133
134 Equivalent to ``get(False)``.
135
136Two methods are offered to support tracking whether enqueued tasks have been
137fully processed by daemon consumer threads.
138
139
140.. method:: Queue.task_done()
141
142 Indicate that a formerly enqueued task is complete. Used by queue consumer
143 threads. For each :meth:`get` used to fetch a task, a subsequent call to
144 :meth:`task_done` tells the queue that the processing on the task is complete.
145
146 If a :meth:`join` is currently blocking, it will resume when all items have been
147 processed (meaning that a :meth:`task_done` call was received for every item
148 that had been :meth:`put` into the queue).
149
150 Raises a :exc:`ValueError` if called more times than there were items placed in
151 the queue.
152
153 .. versionadded:: 2.5
154
155
156.. method:: Queue.join()
157
158 Blocks until all items in the queue have been gotten and processed.
159
160 The count of unfinished tasks goes up whenever an item is added to the queue.
161 The count goes down whenever a consumer thread calls :meth:`task_done` to
162 indicate that the item was retrieved and all work on it is complete. When the
163 count of unfinished tasks drops to zero, join() unblocks.
164
165 .. versionadded:: 2.5
166
167Example of how to wait for enqueued tasks to be completed::
168
169 def worker():
170 while True:
171 item = q.get()
172 do_work(item)
173 q.task_done()
174
175 q = Queue()
176 for i in range(num_worker_threads):
177 t = Thread(target=worker)
178 t.setDaemon(True)
179 t.start()
180
181 for item in source():
182 q.put(item)
183
184 q.join() # block until all tasks are done
185