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