blob: e16d6e98a1d122715923fd2892034a64a2b65afd [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
Alexandre Vassalottif260e442008-05-11 19:59:59 +00002:mod:`queue` --- A synchronized queue class
Georg Brandl116aa622007-08-15 14:28:22 +00003===========================================
4
Alexandre Vassalottif260e442008-05-11 19:59:59 +00005.. module:: queue
Georg Brandl116aa622007-08-15 14:28:22 +00006 :synopsis: A synchronized queue class.
7
8
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
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
25.. class:: Queue(maxsize)
26
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
Christian Heimes679db4a2008-01-18 09:56:22 +000032
Raymond Hettinger35641462008-01-17 00:13:27 +000033.. class:: LifoQueue(maxsize)
34
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
Raymond Hettinger35641462008-01-17 00:13:27 +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 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
Raymond Hettinger1d7f4b22009-03-09 12:54:35 +000064.. seealso::
65
66 :class:`collections.deque` is an alternative implementation of unbounded
67 queues with fast atomic :func:`append` and :func:`popleft` operations that
68 do not require locking.
69
Georg Brandl116aa622007-08-15 14:28:22 +000070
71.. _queueobjects:
72
73Queue Objects
74-------------
75
Christian Heimes292d3512008-02-03 16:51:08 +000076Queue objects (:class:`Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
Georg Brandl48310cd2009-01-03 21:18:54 +000077provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +000078
79
80.. method:: Queue.qsize()
81
Guido van Rossum7736b5b2008-01-15 21:44:53 +000082 Return the approximate size of the queue. Note, qsize() > 0 doesn't
83 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
84 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +000085
86
Raymond Hettinger47aa9892009-03-07 14:07:37 +000087.. method:: Queue.empty()
88
89 Return ``True`` if the queue is empty, ``False`` otherwise. If empty()
90 returns ``True`` it doesn't guarantee that a subsequent call to put()
91 will not block. Similarly, if empty() returns ``False`` it doesn't
92 guarantee that a subsequent call to get() will not block.
93
94
95.. method:: Queue.full()
96
97 Return ``True`` if the queue is full, ``False`` otherwise. If full()
98 returns ``True`` it doesn't guarantee that a subsequent call to get()
99 will not block. Similarly, if full() returns ``False`` it doesn't
100 guarantee that a subsequent call to put() will not block.
101
102
Georg Brandl116aa622007-08-15 14:28:22 +0000103.. method:: Queue.put(item[, block[, timeout]])
104
105 Put *item* into the queue. If optional args *block* is true and *timeout* is
106 None (the default), block if necessary until a free slot is available. If
107 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
108 the :exc:`Full` exception if no free slot was available within that time.
109 Otherwise (*block* is false), put an item on the queue if a free slot is
110 immediately available, else raise the :exc:`Full` exception (*timeout* is
111 ignored in that case).
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114.. method:: Queue.put_nowait(item)
115
116 Equivalent to ``put(item, False)``.
117
118
119.. method:: Queue.get([block[, timeout]])
120
121 Remove and return an item from the queue. If optional args *block* is true and
122 *timeout* is None (the default), block if necessary until an item is available.
123 If *timeout* is a positive number, it blocks at most *timeout* seconds and
124 raises the :exc:`Empty` exception if no item was available within that time.
125 Otherwise (*block* is false), return an item if one is immediately available,
126 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
127
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129.. method:: Queue.get_nowait()
130
131 Equivalent to ``get(False)``.
132
133Two methods are offered to support tracking whether enqueued tasks have been
134fully processed by daemon consumer threads.
135
136
137.. method:: Queue.task_done()
138
139 Indicate that a formerly enqueued task is complete. Used by queue consumer
140 threads. For each :meth:`get` used to fetch a task, a subsequent call to
141 :meth:`task_done` tells the queue that the processing on the task is complete.
142
143 If a :meth:`join` is currently blocking, it will resume when all items have been
144 processed (meaning that a :meth:`task_done` call was received for every item
145 that had been :meth:`put` into the queue).
146
147 Raises a :exc:`ValueError` if called more times than there were items placed in
148 the queue.
149
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151.. method:: Queue.join()
152
153 Blocks until all items in the queue have been gotten and processed.
154
155 The count of unfinished tasks goes up whenever an item is added to the queue.
156 The count goes down whenever a consumer thread calls :meth:`task_done` to
157 indicate that the item was retrieved and all work on it is complete. When the
Raymond Hettinger28c013d2009-03-10 00:07:25 +0000158 count of unfinished tasks drops to zero, :meth:`join` unblocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161Example of how to wait for enqueued tasks to be completed::
162
Georg Brandl48310cd2009-01-03 21:18:54 +0000163 def worker():
164 while True:
165 item = q.get()
166 do_work(item)
167 q.task_done()
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Georg Brandl48310cd2009-01-03 21:18:54 +0000169 q = Queue()
170 for i in range(num_worker_threads):
Georg Brandl116aa622007-08-15 14:28:22 +0000171 t = Thread(target=worker)
Benjamin Petersone8fcbf62009-01-30 02:29:43 +0000172 t.daemon = True
Georg Brandl48310cd2009-01-03 21:18:54 +0000173 t.start()
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175 for item in source():
Georg Brandl48310cd2009-01-03 21:18:54 +0000176 q.put(item)
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178 q.join() # block until all tasks are done
179