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