blob: 6ee97029abeb0395d7338584b51ddb82c3e31bde [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
Georg Brandla6168f92008-05-25 07:20:14 +000027The :mod:`Queue` module defines the following classes and exceptions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000028
29.. class:: Queue(maxsize)
30
Raymond Hettinger171f3912008-01-16 23:38:16 +000031 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl8ec7f652007-08-15 14:28:01 +000032 limit on the number of items that can be placed in the queue. Insertion will
33 block once this size has been reached, until queue items are consumed. If
34 *maxsize* is less than or equal to zero, the queue size is infinite.
35
Raymond Hettinger171f3912008-01-16 23:38:16 +000036.. class:: LifoQueue(maxsize)
37
38 Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
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
Raymond Hettingerd59f4572008-01-17 08:07:05 +000043 .. versionadded:: 2.6
44
Raymond Hettinger171f3912008-01-16 23:38:16 +000045.. class:: PriorityQueue(maxsize)
46
47 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
48 limit on the number of items that can be placed in the queue. Insertion will
49 block once this size has been reached, until queue items are consumed. If
50 *maxsize* is less than or equal to zero, the queue size is infinite.
51
52 The lowest valued entries are retrieved first (the lowest valued entry is the
53 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
54 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
Raymond Hettingerd59f4572008-01-17 08:07:05 +000056 .. versionadded:: 2.6
57
Georg Brandl8ec7f652007-08-15 14:28:01 +000058.. exception:: Empty
59
60 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
61 on a :class:`Queue` object which is empty.
62
63
64.. exception:: Full
65
66 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
67 on a :class:`Queue` object which is full.
68
69
70.. _queueobjects:
71
72Queue Objects
73-------------
74
Brett Cannon89dfbe32008-02-03 02:34:14 +000075Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandla6168f92008-05-25 07:20:14 +000076provide the public methods described below.
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
78
79.. method:: Queue.qsize()
80
Raymond Hettinger907cda62008-01-15 05:46:43 +000081 Return the approximate size of the queue. Note, qsize() > 0 doesn't
82 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
Skip Montanarof233b0c2008-01-15 03:40:20 +000083 guarantee that put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000084
85
86.. method:: Queue.empty()
87
Skip Montanarof233b0c2008-01-15 03:40:20 +000088 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
89 returns ``True`` it doesn't guarantee that a subsequent call to put()
90 will not block. Similarly, if empty() returns ``False`` it doesn't
91 guarantee that a subsequent call to get() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
93
94.. method:: Queue.full()
95
Skip Montanarof233b0c2008-01-15 03:40:20 +000096 Return ``True`` if the queue is full, ``False`` otherwise. If full()
97 returns ``True`` it doesn't guarantee that a subsequent call to get()
98 will not block. Similarly, if full() returns ``False`` it doesn't
99 guarantee that a subsequent call to put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000100
101
102.. method:: Queue.put(item[, block[, timeout]])
103
104 Put *item* into the queue. If optional args *block* is true and *timeout* is
105 None (the default), block if necessary until a free slot is available. If
106 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
107 the :exc:`Full` exception if no free slot was available within that time.
108 Otherwise (*block* is false), put an item on the queue if a free slot is
109 immediately available, else raise the :exc:`Full` exception (*timeout* is
110 ignored in that case).
111
112 .. versionadded:: 2.3
113 The *timeout* parameter.
114
115
116.. method:: Queue.put_nowait(item)
117
118 Equivalent to ``put(item, False)``.
119
120
121.. method:: Queue.get([block[, timeout]])
122
123 Remove and return an item from the queue. If optional args *block* is true and
124 *timeout* is None (the default), block if necessary until an item is available.
125 If *timeout* is a positive number, it blocks at most *timeout* seconds and
126 raises the :exc:`Empty` exception if no item was available within that time.
127 Otherwise (*block* is false), return an item if one is immediately available,
128 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
129
130 .. versionadded:: 2.3
131 The *timeout* parameter.
132
133
134.. method:: Queue.get_nowait()
135
136 Equivalent to ``get(False)``.
137
138Two methods are offered to support tracking whether enqueued tasks have been
139fully processed by daemon consumer threads.
140
141
142.. method:: Queue.task_done()
143
144 Indicate that a formerly enqueued task is complete. Used by queue consumer
145 threads. For each :meth:`get` used to fetch a task, a subsequent call to
146 :meth:`task_done` tells the queue that the processing on the task is complete.
147
148 If a :meth:`join` is currently blocking, it will resume when all items have been
149 processed (meaning that a :meth:`task_done` call was received for every item
150 that had been :meth:`put` into the queue).
151
152 Raises a :exc:`ValueError` if called more times than there were items placed in
153 the queue.
154
155 .. versionadded:: 2.5
156
157
158.. method:: Queue.join()
159
160 Blocks until all items in the queue have been gotten and processed.
161
162 The count of unfinished tasks goes up whenever an item is added to the queue.
163 The count goes down whenever a consumer thread calls :meth:`task_done` to
164 indicate that the item was retrieved and all work on it is complete. When the
165 count of unfinished tasks drops to zero, join() unblocks.
166
167 .. versionadded:: 2.5
168
169Example of how to wait for enqueued tasks to be completed::
170
Georg Brandla6168f92008-05-25 07:20:14 +0000171 def worker():
172 while True:
173 item = q.get()
174 do_work(item)
175 q.task_done()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176
Georg Brandla6168f92008-05-25 07:20:14 +0000177 q = Queue()
178 for i in range(num_worker_threads):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179 t = Thread(target=worker)
180 t.setDaemon(True)
Georg Brandla6168f92008-05-25 07:20:14 +0000181 t.start()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183 for item in source():
Georg Brandla6168f92008-05-25 07:20:14 +0000184 q.put(item)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
186 q.join() # block until all tasks are done
187