blob: bc3821e2eb9c89caca12ae1bfa62b32f45fe55b0 [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
Alexandre Vassalottif260e442008-05-11 19:59:59 +00009The :mod:`queue` module implements multi-producer, multi-consumer queues.
Thomas Wouters89d996e2007-09-08 17:39:28 +000010It is especially useful in threaded programming when information must be
Georg Brandl116aa622007-08-15 14:28:22 +000011exchanged safely between multiple threads. The :class:`Queue` class in this
12module implements all the required locking semantics. It depends on the
Thomas Wouters89d996e2007-09-08 17:39:28 +000013availability of thread support in Python; see the :mod:`threading`
14module.
Georg Brandl116aa622007-08-15 14:28:22 +000015
Raymond Hettinger35641462008-01-17 00:13:27 +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 Brandl116aa622007-08-15 14:28:22 +000022
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000023
Alexandre Vassalottif260e442008-05-11 19:59:59 +000024The :mod:`queue` module defines the following classes and exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +000025
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000026.. class:: Queue(maxsize=0)
Georg Brandl116aa622007-08-15 14:28:22 +000027
Raymond Hettinger35641462008-01-17 00:13:27 +000028 Constructor for a FIFO queue. *maxsize* is an integer that sets the upperbound
Georg Brandl116aa622007-08-15 14:28:22 +000029 limit on the number of items that can be placed in the queue. Insertion will
30 block once this size has been reached, until queue items are consumed. If
31 *maxsize* is less than or equal to zero, the queue size is infinite.
32
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000033.. class:: LifoQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000034
35 Constructor for a LIFO queue. *maxsize* is an integer that sets the upperbound
36 limit on the number of items that can be placed in the queue. Insertion will
37 block once this size has been reached, until queue items are consumed. If
38 *maxsize* is less than or equal to zero, the queue size is infinite.
39
Christian Heimes679db4a2008-01-18 09:56:22 +000040
Andrew M. Kuchling2b600e52010-02-26 13:35:56 +000041.. class:: PriorityQueue(maxsize=0)
Raymond Hettinger35641462008-01-17 00:13:27 +000042
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 Brandl116aa622007-08-15 14:28:22 +000051
Christian Heimes679db4a2008-01-18 09:56:22 +000052
Georg Brandl116aa622007-08-15 14:28:22 +000053.. exception:: Empty
54
55 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
56 on a :class:`Queue` object which is empty.
57
58
59.. exception:: Full
60
61 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
62 on a :class:`Queue` object which is full.
63
64
65.. _queueobjects:
66
67Queue Objects
68-------------
69
Christian Heimes292d3512008-02-03 16:51:08 +000070Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandl48310cd2009-01-03 21:18:54 +000071provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73
74.. method:: Queue.qsize()
75
Guido van Rossum7736b5b2008-01-15 21:44:53 +000076 Return the approximate size of the queue. Note, qsize() > 0 doesn't
77 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
78 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +000079
80
Raymond Hettinger47aa9892009-03-07 14:07:37 +000081.. method:: Queue.empty()
82
83 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
84 returns ``True`` it doesn't guarantee that a subsequent call to put()
85 will not block. Similarly, if empty() returns ``False`` it doesn't
86 guarantee that a subsequent call to get() will not block.
87
88
89.. method:: Queue.full()
90
91 Return ``True`` if the queue is full, ``False`` otherwise. If full()
92 returns ``True`` it doesn't guarantee that a subsequent call to get()
93 will not block. Similarly, if full() returns ``False`` it doesn't
94 guarantee that a subsequent call to put() will not block.
95
96
Georg Brandl18244152009-09-02 20:34:52 +000097.. method:: Queue.put(item, block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +000098
99 Put *item* into the queue. If optional args *block* is true and *timeout* is
100 None (the default), block if necessary until a free slot is available. If
101 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
102 the :exc:`Full` exception if no free slot was available within that time.
103 Otherwise (*block* is false), put an item on the queue if a free slot is
104 immediately available, else raise the :exc:`Full` exception (*timeout* is
105 ignored in that case).
106
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108.. method:: Queue.put_nowait(item)
109
110 Equivalent to ``put(item, False)``.
111
112
Georg Brandl18244152009-09-02 20:34:52 +0000113.. method:: Queue.get(block=True, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000114
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
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123.. method:: Queue.get_nowait()
124
125 Equivalent to ``get(False)``.
126
127Two methods are offered to support tracking whether enqueued tasks have been
128fully processed by daemon consumer threads.
129
130
131.. method:: Queue.task_done()
132
133 Indicate that a formerly enqueued task is complete. Used by queue consumer
134 threads. For each :meth:`get` used to fetch a task, a subsequent call to
135 :meth:`task_done` tells the queue that the processing on the task is complete.
136
137 If a :meth:`join` is currently blocking, it will resume when all items have been
138 processed (meaning that a :meth:`task_done` call was received for every item
139 that had been :meth:`put` into the queue).
140
141 Raises a :exc:`ValueError` if called more times than there were items placed in
142 the queue.
143
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145.. method:: Queue.join()
146
147 Blocks until all items in the queue have been gotten and processed.
148
149 The count of unfinished tasks goes up whenever an item is added to the queue.
150 The count goes down whenever a consumer thread calls :meth:`task_done` to
151 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000152 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155Example of how to wait for enqueued tasks to be completed::
156
Georg Brandl48310cd2009-01-03 21:18:54 +0000157 def worker():
158 while True:
159 item = q.get()
160 do_work(item)
161 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Georg Brandl48310cd2009-01-03 21:18:54 +0000163 q = Queue()
164 for i in range(num_worker_threads):
Georg Brandl116aa622007-08-15 14:28:22 +0000165 t = Thread(target=worker)
Benjamin Petersone8fcbf62009-01-30 02:29:43 +0000166 t.daemon = True
Georg Brandl48310cd2009-01-03 21:18:54 +0000167 t.start()
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169 for item in source():
Georg Brandl48310cd2009-01-03 21:18:54 +0000170 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172 q.join() # block until all tasks are done
173
Antoine Pitrou696efdd2011-01-07 19:16:12 +0000174
175.. seealso::
176
177 Class :class:`multiprocessing.Queue`
178 A queue class for use in a multi-processing (rather than multi-threading)
179 context.
180
Georg Brandl2f2a9f72011-01-07 20:58:25 +0000181 :class:`collections.deque` is an alternative implementation of unbounded
Raymond Hettingerfc902132011-01-07 20:33:09 +0000182 queues with fast atomic :func:`append` and :func:`popleft` operations that
183 do not require locking.
184