blob: 67c5c6f85376de7c071f00e24890ecb5eacb0b37 [file] [log] [blame]
Eli Bendersky877f2e42011-07-17 05:54:06 +03001: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::
Ezio Melotti510ff542012-05-03 19:21:40 +03008 The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3. The
Georg Brandla6168f92008-05-25 07:20:14 +00009 :term:`2to3` tool will automatically adapt imports when converting your
Ezio Melotti510ff542012-05-03 19:21:40 +030010 sources to Python 3.
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
Éric Araujo29a0b572011-08-19 02:14:03 +020012**Source code:** :source:`Lib/Queue.py`
13
14--------------
Georg Brandl7a148c22008-05-12 10:03:16 +000015
Georg Brandla6168f92008-05-25 07:20:14 +000016The :mod:`Queue` module implements multi-producer, multi-consumer queues.
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000017It is especially useful in threaded programming when information must be
Georg Brandl8ec7f652007-08-15 14:28:01 +000018exchanged safely between multiple threads. The :class:`Queue` class in this
19module implements all the required locking semantics. It depends on the
Mark Summerfieldfcb444a2007-09-04 08:16:15 +000020availability of thread support in Python; see the :mod:`threading`
21module.
Georg Brandl8ec7f652007-08-15 14:28:01 +000022
Raymond Hettinger171f3912008-01-16 23:38:16 +000023Implements three types of queue whose only difference is the order that
24the entries are retrieved. In a FIFO queue, the first tasks added are
25the first retrieved. In a LIFO queue, the most recently added entry is
26the first retrieved (operating like a stack). With a priority queue,
27the entries are kept sorted (using the :mod:`heapq` module) and the
28lowest valued entry is retrieved first.
Georg Brandl8ec7f652007-08-15 14:28:01 +000029
Georg Brandla6168f92008-05-25 07:20:14 +000030The :mod:`Queue` module defines the following classes and exceptions:
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Andrew M. Kuchling9aeeffa2010-02-26 13:22:50 +000032.. class:: Queue(maxsize=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +000033
Raymond Hettinger171f3912008-01-16 23:38:16 +000034 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl8ec7f652007-08-15 14:28:01 +000035 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
Andrew M. Kuchling9aeeffa2010-02-26 13:22:50 +000039.. class:: LifoQueue(maxsize=0)
Raymond Hettinger171f3912008-01-16 23:38:16 +000040
41 Constructor for a LIFO 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
Raymond Hettingerd59f4572008-01-17 08:07:05 +000046 .. versionadded:: 2.6
47
Andrew M. Kuchling9aeeffa2010-02-26 13:22:50 +000048.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger171f3912008-01-16 23:38:16 +000049
50 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
51 limit on the number of items that can be placed in the queue. Insertion will
52 block once this size has been reached, until queue items are consumed. If
53 *maxsize* is less than or equal to zero, the queue size is infinite.
54
55 The lowest valued entries are retrieved first (the lowest valued entry is the
56 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
57 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000058
Raymond Hettingerd59f4572008-01-17 08:07:05 +000059 .. versionadded:: 2.6
60
Georg Brandl8ec7f652007-08-15 14:28:01 +000061.. exception:: Empty
62
63 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
64 on a :class:`Queue` object which is empty.
65
66
67.. exception:: Full
68
69 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
70 on a :class:`Queue` object which is full.
71
Raymond Hettinger9324ed82009-03-09 12:56:23 +000072.. seealso::
73
74 :class:`collections.deque` is an alternative implementation of unbounded
75 queues with fast atomic :func:`append` and :func:`popleft` operations that
76 do not require locking.
77
Georg Brandl8ec7f652007-08-15 14:28:01 +000078
79.. _queueobjects:
80
81Queue Objects
82-------------
83
Brett Cannon89dfbe32008-02-03 02:34:14 +000084Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandla6168f92008-05-25 07:20:14 +000085provide the public methods described below.
Georg Brandl8ec7f652007-08-15 14:28:01 +000086
87
88.. method:: Queue.qsize()
89
Raymond Hettinger907cda62008-01-15 05:46:43 +000090 Return the approximate size of the queue. Note, qsize() > 0 doesn't
91 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
Skip Montanarof233b0c2008-01-15 03:40:20 +000092 guarantee that put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +000093
94
95.. method:: Queue.empty()
96
Skip Montanarof233b0c2008-01-15 03:40:20 +000097 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
98 returns ``True`` it doesn't guarantee that a subsequent call to put()
99 will not block. Similarly, if empty() returns ``False`` it doesn't
100 guarantee that a subsequent call to get() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101
102
103.. method:: Queue.full()
104
Skip Montanarof233b0c2008-01-15 03:40:20 +0000105 Return ``True`` if the queue is full, ``False`` otherwise. If full()
106 returns ``True`` it doesn't guarantee that a subsequent call to get()
107 will not block. Similarly, if full() returns ``False`` it doesn't
108 guarantee that a subsequent call to put() will not block.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000109
110
111.. method:: Queue.put(item[, block[, timeout]])
112
113 Put *item* into the queue. If optional args *block* is true and *timeout* is
114 None (the default), block if necessary until a free slot is available. If
115 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
116 the :exc:`Full` exception if no free slot was available within that time.
117 Otherwise (*block* is false), put an item on the queue if a free slot is
118 immediately available, else raise the :exc:`Full` exception (*timeout* is
119 ignored in that case).
120
121 .. versionadded:: 2.3
122 The *timeout* parameter.
123
124
125.. method:: Queue.put_nowait(item)
126
127 Equivalent to ``put(item, False)``.
128
129
130.. method:: Queue.get([block[, timeout]])
131
132 Remove and return an item from the queue. If optional args *block* is true and
133 *timeout* is None (the default), block if necessary until an item is available.
134 If *timeout* is a positive number, it blocks at most *timeout* seconds and
135 raises the :exc:`Empty` exception if no item was available within that time.
136 Otherwise (*block* is false), return an item if one is immediately available,
137 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
138
139 .. versionadded:: 2.3
140 The *timeout* parameter.
141
142
143.. method:: Queue.get_nowait()
144
145 Equivalent to ``get(False)``.
146
147Two methods are offered to support tracking whether enqueued tasks have been
148fully processed by daemon consumer threads.
149
150
151.. method:: Queue.task_done()
152
153 Indicate that a formerly enqueued task is complete. Used by queue consumer
154 threads. For each :meth:`get` used to fetch a task, a subsequent call to
155 :meth:`task_done` tells the queue that the processing on the task is complete.
156
157 If a :meth:`join` is currently blocking, it will resume when all items have been
158 processed (meaning that a :meth:`task_done` call was received for every item
159 that had been :meth:`put` into the queue).
160
161 Raises a :exc:`ValueError` if called more times than there were items placed in
162 the queue.
163
164 .. versionadded:: 2.5
165
166
167.. method:: Queue.join()
168
169 Blocks until all items in the queue have been gotten and processed.
170
171 The count of unfinished tasks goes up whenever an item is added to the queue.
172 The count goes down whenever a consumer thread calls :meth:`task_done` to
173 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettingerf4ea9292009-03-10 00:06:05 +0000174 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
176 .. versionadded:: 2.5
177
178Example of how to wait for enqueued tasks to be completed::
179
Georg Brandla6168f92008-05-25 07:20:14 +0000180 def worker():
181 while True:
182 item = q.get()
183 do_work(item)
184 q.task_done()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
Georg Brandla6168f92008-05-25 07:20:14 +0000186 q = Queue()
187 for i in range(num_worker_threads):
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188 t = Thread(target=worker)
Benjamin Petersone047d792009-10-20 03:14:10 +0000189 t.daemon = True
Georg Brandla6168f92008-05-25 07:20:14 +0000190 t.start()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191
192 for item in source():
Georg Brandla6168f92008-05-25 07:20:14 +0000193 q.put(item)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195 q.join() # block until all tasks are done
196