blob: bc35dfe40e1e42e46ce6b3c54efe6718dda3b463 [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
Raymond Hettinger10480942011-01-10 03:26:08 +00007**Source code:** :source:`Lib/queue.py`
Georg Brandl116aa622007-08-15 14:28:22 +00008
Raymond Hettinger4f707fd2011-01-10 19:54:11 +00009--------------
10
Alexandre Vassalottif260e442008-05-11 19:59:59 +000011The :mod:`queue` module implements multi-producer, multi-consumer queues.
Thomas Wouters89d996e2007-09-08 17:39:28 +000012It is especially useful in threaded programming when information must be
Georg Brandl116aa622007-08-15 14:28:22 +000013exchanged safely between multiple threads. The :class:`Queue` class in this
14module implements all the required locking semantics. It depends on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000015availability of thread support in Python; see the :mod:`threading`
16module.
Georg Brandl116aa622007-08-15 14:28:22 +000017
R David Murrayb98b37f2012-05-08 21:28:24 -040018The module implements three types of queue, which differ only in the order in
19which the entries are retrieved. In a FIFO queue, the first tasks added are
Raymond Hettinger35641462008-01-17 00:13:27 +000020the first retrieved. In a LIFO queue, the most recently added entry is
21the first retrieved (operating like a stack). With a priority queue,
22the entries are kept sorted (using the :mod:`heapq` module) and the
23lowest valued entry is retrieved first.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000025
Alexandre Vassalottif260e442008-05-11 19:59:59 +000026The :mod:`queue` module defines the following classes and exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +000027
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000028.. class:: Queue(maxsize=0)
Georg Brandl116aa622007-08-15 14:28:22 +000029
Raymond Hettinger35641462008-01-17 00:13:27 +000030 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl116aa622007-08-15 14:28:22 +000031 limit on the number of items that can be placed in the queue. Insertion will
32 block once this size has been reached, until queue items are consumed. If
33 *maxsize* is less than or equal to zero, the queue size is infinite.
34
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000035.. class:: LifoQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000036
37 Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
38 limit on the number of items that can be placed in the queue. Insertion will
39 block once this size has been reached, until queue items are consumed. If
40 *maxsize* is less than or equal to zero, the queue size is infinite.
41
Christian Heimes679db4a2008-01-18 09:56:22 +000042
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000043.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000044
45 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
46 limit on the number of items that can be placed in the queue. Insertion will
47 block once this size has been reached, until queue items are consumed. If
48 *maxsize* is less than or equal to zero, the queue size is infinite.
49
50 The lowest valued entries are retrieved first (the lowest valued entry is the
51 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
52 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl116aa622007-08-15 14:28:22 +000053
Christian Heimes679db4a2008-01-18 09:56:22 +000054
Georg Brandl116aa622007-08-15 14:28:22 +000055.. exception:: Empty
56
57 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
58 on a :class:`Queue` object which is empty.
59
60
61.. exception:: Full
62
63 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
64 on a :class:`Queue` object which is full.
65
66
67.. _queueobjects:
68
69Queue Objects
70-------------
71
Christian Heimes292d3512008-02-03 16:51:08 +000072Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandl48310cd2009-01-03 21:18:54 +000073provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
76.. method:: Queue.qsize()
77
Guido van Rossum7736b5b2008-01-15 21:44:53 +000078 Return the approximate size of the queue. Note, qsize() > 0 doesn't
79 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
80 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +000081
82
Raymond Hettinger47aa9892009-03-07 14:07:37 +000083.. method:: Queue.empty()
84
85 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
86 returns ``True`` it doesn't guarantee that a subsequent call to put()
87 will not block. Similarly, if empty() returns ``False`` it doesn't
88 guarantee that a subsequent call to get() will not block.
89
90
91.. method:: Queue.full()
92
93 Return ``True`` if the queue is full, ``False`` otherwise. If full()
94 returns ``True`` it doesn't guarantee that a subsequent call to get()
95 will not block. Similarly, if full() returns ``False`` it doesn't
96 guarantee that a subsequent call to put() will not block.
97
98
Georg Brandl18244152009-09-02 20:34:52 +000099.. method:: Queue.put(item, block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101 Put *item* into the queue. If optional args *block* is true and *timeout* is
102 None (the default), block if necessary until a free slot is available. If
103 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
104 the :exc:`Full` exception if no free slot was available within that time.
105 Otherwise (*block* is false), put an item on the queue if a free slot is
106 immediately available, else raise the :exc:`Full` exception (*timeout* is
107 ignored in that case).
108
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110.. method:: Queue.put_nowait(item)
111
112 Equivalent to ``put(item, False)``.
113
114
Georg Brandl18244152009-09-02 20:34:52 +0000115.. method:: Queue.get(block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117 Remove and return an item from the queue. If optional args *block* is true and
118 *timeout* is None (the default), block if necessary until an item is available.
119 If *timeout* is a positive number, it blocks at most *timeout* seconds and
120 raises the :exc:`Empty` exception if no item was available within that time.
121 Otherwise (*block* is false), return an item if one is immediately available,
122 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
123
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125.. method:: Queue.get_nowait()
126
127 Equivalent to ``get(False)``.
128
129Two methods are offered to support tracking whether enqueued tasks have been
130fully processed by daemon consumer threads.
131
132
133.. method:: Queue.task_done()
134
135 Indicate that a formerly enqueued task is complete. Used by queue consumer
136 threads. For each :meth:`get` used to fetch a task, a subsequent call to
137 :meth:`task_done` tells the queue that the processing on the task is complete.
138
139 If a :meth:`join` is currently blocking, it will resume when all items have been
140 processed (meaning that a :meth:`task_done` call was received for every item
141 that had been :meth:`put` into the queue).
142
143 Raises a :exc:`ValueError` if called more times than there were items placed in
144 the queue.
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147.. method:: Queue.join()
148
149 Blocks until all items in the queue have been gotten and processed.
150
151 The count of unfinished tasks goes up whenever an item is added to the queue.
152 The count goes down whenever a consumer thread calls :meth:`task_done` to
153 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000154 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157Example of how to wait for enqueued tasks to be completed::
158
Georg Brandl48310cd2009-01-03 21:18:54 +0000159 def worker():
160 while True:
161 item = q.get()
162 do_work(item)
163 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000164
Georg Brandl48310cd2009-01-03 21:18:54 +0000165 q = Queue()
166 for i in range(num_worker_threads):
Georg Brandl116aa622007-08-15 14:28:22 +0000167 t = Thread(target=worker)
Benjamin Petersone8fcbf62009-01-30 02:29:43 +0000168 t.daemon = True
Georg Brandl48310cd2009-01-03 21:18:54 +0000169 t.start()
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171 for item in source():
Georg Brandl48310cd2009-01-03 21:18:54 +0000172 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174 q.join() # block until all tasks are done
175
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000176
177.. seealso::
178
179 Class :class:`multiprocessing.Queue`
180 A queue class for use in a multi-processing (rather than multi-threading)
181 context.
182
Georg Brandl2f2a9f72011-01-07 20:58:25 +0000183 :class:`collections.deque` is an alternative implementation of unbounded
Raymond Hettingerfc902132011-01-07 20:33:09 +0000184 queues with fast atomic :func:`append` and :func:`popleft` operations that
185 do not require locking.
186