blob: 582f2cd0957daf378bcde35b4833574fce0538ef [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`Queue` --- A synchronized queue class
3===========================================
4
5.. module:: Queue
6 :synopsis: A synchronized queue class.
7
8
Raymond Hettinger35641462008-01-17 00:13:27 +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
Raymond Hettinger35641462008-01-17 00:13:27 +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 .. versionadded:: 2.6
41
42
Raymond Hettinger35641462008-01-17 00:13:27 +000043.. class:: PriorityQueue(maxsize)
44
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 .. versionadded:: 2.6
55
56
Georg Brandl116aa622007-08-15 14:28:22 +000057.. exception:: Empty
58
59 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
60 on a :class:`Queue` object which is empty.
61
62
63.. exception:: Full
64
65 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
66 on a :class:`Queue` object which is full.
67
68
69.. _queueobjects:
70
71Queue Objects
72-------------
73
Raymond Hettinger35641462008-01-17 00:13:27 +000074Queue objects (:class:``Queue``, :class:``LifoQueue``, or :class:``PriorityQueue``
75provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +000076
77
78.. method:: Queue.qsize()
79
Guido van Rossum7736b5b2008-01-15 21:44:53 +000080 Return the approximate size of the queue. Note, qsize() > 0 doesn't
81 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
82 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +000083
84
Georg Brandl116aa622007-08-15 14:28:22 +000085.. method:: Queue.put(item[, block[, timeout]])
86
87 Put *item* into the queue. If optional args *block* is true and *timeout* is
88 None (the default), block if necessary until a free slot is available. If
89 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
90 the :exc:`Full` exception if no free slot was available within that time.
91 Otherwise (*block* is false), put an item on the queue if a free slot is
92 immediately available, else raise the :exc:`Full` exception (*timeout* is
93 ignored in that case).
94
Georg Brandl116aa622007-08-15 14:28:22 +000095
96.. method:: Queue.put_nowait(item)
97
98 Equivalent to ``put(item, False)``.
99
100
101.. method:: Queue.get([block[, timeout]])
102
103 Remove and return an item from the queue. If optional args *block* is true and
104 *timeout* is None (the default), block if necessary until an item is available.
105 If *timeout* is a positive number, it blocks at most *timeout* seconds and
106 raises the :exc:`Empty` exception if no item was available within that time.
107 Otherwise (*block* is false), return an item if one is immediately available,
108 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
109
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111.. method:: Queue.get_nowait()
112
113 Equivalent to ``get(False)``.
114
115Two methods are offered to support tracking whether enqueued tasks have been
116fully processed by daemon consumer threads.
117
118
119.. method:: Queue.task_done()
120
121 Indicate that a formerly enqueued task is complete. Used by queue consumer
122 threads. For each :meth:`get` used to fetch a task, a subsequent call to
123 :meth:`task_done` tells the queue that the processing on the task is complete.
124
125 If a :meth:`join` is currently blocking, it will resume when all items have been
126 processed (meaning that a :meth:`task_done` call was received for every item
127 that had been :meth:`put` into the queue).
128
129 Raises a :exc:`ValueError` if called more times than there were items placed in
130 the queue.
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133.. method:: Queue.join()
134
135 Blocks until all items in the queue have been gotten and processed.
136
137 The count of unfinished tasks goes up whenever an item is added to the queue.
138 The count goes down whenever a consumer thread calls :meth:`task_done` to
139 indicate that the item was retrieved and all work on it is complete. When the
140 count of unfinished tasks drops to zero, join() unblocks.
141
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143Example of how to wait for enqueued tasks to be completed::
144
145 def worker():
146 while True:
147 item = q.get()
148 do_work(item)
149 q.task_done()
150
151 q = Queue()
152 for i in range(num_worker_threads):
153 t = Thread(target=worker)
154 t.setDaemon(True)
155 t.start()
156
157 for item in source():
158 q.put(item)
159
160 q.join() # block until all tasks are done
161