blob: 8a767c67349f12355ee25c26e72c97277eb4e7ea [file] [log] [blame]
Alexandre Vassalottif260e442008-05-11 19:59:59 +00001:mod:`queue` --- A synchronized queue class
Georg Brandl116aa622007-08-15 14:28:22 +00002===========================================
3
Alexandre Vassalottif260e442008-05-11 19:59:59 +00004.. module:: queue
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: A synchronized queue class.
6
7
Alexandre Vassalottif260e442008-05-11 19:59:59 +00008The :mod:`queue` module implements multi-producer, multi-consumer queues.
Thomas Wouters89d996e2007-09-08 17:39:28 +00009It is especially useful in threaded programming when information must be
Georg Brandl116aa622007-08-15 14:28:22 +000010exchanged safely between multiple threads. The :class:`Queue` class in this
11module implements all the required locking semantics. It depends on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000012availability of thread support in Python; see the :mod:`threading`
13module.
Georg Brandl116aa622007-08-15 14:28:22 +000014
Raymond Hettinger35641462008-01-17 00:13:27 +000015Implements three types of queue whose only difference is the order that
16the entries are retrieved. In a FIFO queue, the first tasks added are
17the first retrieved. In a LIFO queue, the most recently added entry is
18the first retrieved (operating like a stack). With a priority queue,
19the entries are kept sorted (using the :mod:`heapq` module) and the
20lowest valued entry is retrieved first.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000022
Alexandre Vassalottif260e442008-05-11 19:59:59 +000023The :mod:`queue` module defines the following classes and exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +000024
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000025.. class:: Queue(maxsize=0)
Georg Brandl116aa622007-08-15 14:28:22 +000026
Raymond Hettinger35641462008-01-17 00:13:27 +000027 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl116aa622007-08-15 14:28:22 +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
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000032.. class:: LifoQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000033
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
Christian Heimes679db4a2008-01-18 09:56:22 +000039
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000040.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000041
42 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
43 limit on the number of items that can be placed in the queue. Insertion will
44 block once this size has been reached, until queue items are consumed. If
45 *maxsize* is less than or equal to zero, the queue size is infinite.
46
47 The lowest valued entries are retrieved first (the lowest valued entry is the
48 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
49 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl116aa622007-08-15 14:28:22 +000050
Christian Heimes679db4a2008-01-18 09:56:22 +000051
Georg Brandl116aa622007-08-15 14:28:22 +000052.. exception:: Empty
53
54 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
55 on a :class:`Queue` object which is empty.
56
57
58.. exception:: Full
59
60 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
61 on a :class:`Queue` object which is full.
62
Raymond Hettinger1d7f4b22009-03-09 12:54:35 +000063.. seealso::
64
65 :class:`collections.deque` is an alternative implementation of unbounded
66 queues with fast atomic :func:`append` and :func:`popleft` operations that
67 do not require locking.
68
Georg Brandl116aa622007-08-15 14:28:22 +000069
70.. _queueobjects:
71
72Queue Objects
73-------------
74
Christian Heimes292d3512008-02-03 16:51:08 +000075Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandl48310cd2009-01-03 21:18:54 +000076provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78
79.. method:: Queue.qsize()
80
Guido van Rossum7736b5b2008-01-15 21:44:53 +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
83 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +000084
85
Raymond Hettinger47aa9892009-03-07 14:07:37 +000086.. method:: Queue.empty()
87
88 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.
92
93
94.. method:: Queue.full()
95
96 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.
100
101
Georg Brandl18244152009-09-02 20:34:52 +0000102.. method:: Queue.put(item, block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000103
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
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113.. method:: Queue.put_nowait(item)
114
115 Equivalent to ``put(item, False)``.
116
117
Georg Brandl18244152009-09-02 20:34:52 +0000118.. method:: Queue.get(block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120 Remove and return an item from the queue. If optional args *block* is true and
121 *timeout* is None (the default), block if necessary until an item is available.
122 If *timeout* is a positive number, it blocks at most *timeout* seconds and
123 raises the :exc:`Empty` exception if no item was available within that time.
124 Otherwise (*block* is false), return an item if one is immediately available,
125 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128.. method:: Queue.get_nowait()
129
130 Equivalent to ``get(False)``.
131
132Two methods are offered to support tracking whether enqueued tasks have been
133fully processed by daemon consumer threads.
134
135
136.. method:: Queue.task_done()
137
138 Indicate that a formerly enqueued task is complete. Used by queue consumer
139 threads. For each :meth:`get` used to fetch a task, a subsequent call to
140 :meth:`task_done` tells the queue that the processing on the task is complete.
141
142 If a :meth:`join` is currently blocking, it will resume when all items have been
143 processed (meaning that a :meth:`task_done` call was received for every item
144 that had been :meth:`put` into the queue).
145
146 Raises a :exc:`ValueError` if called more times than there were items placed in
147 the queue.
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
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
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000157 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160Example of how to wait for enqueued tasks to be completed::
161
Georg Brandl48310cd2009-01-03 21:18:54 +0000162 def worker():
163 while True:
164 item = q.get()
165 do_work(item)
166 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000167
Georg Brandl48310cd2009-01-03 21:18:54 +0000168 q = Queue()
169 for i in range(num_worker_threads):
Georg Brandl116aa622007-08-15 14:28:22 +0000170 t = Thread(target=worker)
Benjamin Petersone8fcbf62009-01-30 02:29:43 +0000171 t.daemon = True
Georg Brandl48310cd2009-01-03 21:18:54 +0000172 t.start()
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174 for item in source():
Georg Brandl48310cd2009-01-03 21:18:54 +0000175 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000176
177 q.join() # block until all tasks are done
178
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000179
180.. seealso::
181
182 Class :class:`multiprocessing.Queue`
183 A queue class for use in a multi-processing (rather than multi-threading)
184 context.
185
186 Latest version of the :source:`queue module Python source code
187 <Lib/queue.py>`