blob: 5442a76943a2a3916d4c231458662b5b79be69f6 [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
Raymond Hettinger35641462008-01-17 00:13:27 +000032.. class:: LifoQueue(maxsize)
33
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
39.. class:: PriorityQueue(maxsize)
40
41 Constructor for a priority queue. *maxsize* is an integer that sets the upperbound
42 limit on the number of items that can be placed in the queue. Insertion will
43 block once this size has been reached, until queue items are consumed. If
44 *maxsize* is less than or equal to zero, the queue size is infinite.
45
46 The lowest valued entries are retrieved first (the lowest valued entry is the
47 one returned by ``sorted(list(entries))[0]``). A typical pattern for entries
48 is a tuple in the form: ``(priority_number, data)``.
Georg Brandl116aa622007-08-15 14:28:22 +000049
50.. exception:: Empty
51
52 Exception raised when non-blocking :meth:`get` (or :meth:`get_nowait`) is called
53 on a :class:`Queue` object which is empty.
54
55
56.. exception:: Full
57
58 Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
59 on a :class:`Queue` object which is full.
60
61
62.. _queueobjects:
63
64Queue Objects
65-------------
66
Raymond Hettinger35641462008-01-17 00:13:27 +000067Queue objects (:class:``Queue``, :class:``LifoQueue``, or :class:``PriorityQueue``
68provide the public methods described below.
Georg Brandl116aa622007-08-15 14:28:22 +000069
70
71.. method:: Queue.qsize()
72
Guido van Rossum7736b5b2008-01-15 21:44:53 +000073 Return the approximate size of the queue. Note, qsize() > 0 doesn't
74 guarantee that a subsequent get() will not block, nor will qsize() < maxsize
75 guarantee that put() will not block.
Georg Brandl116aa622007-08-15 14:28:22 +000076
77
Georg Brandl116aa622007-08-15 14:28:22 +000078.. method:: Queue.put(item[, block[, timeout]])
79
80 Put *item* into the queue. If optional args *block* is true and *timeout* is
81 None (the default), block if necessary until a free slot is available. If
82 *timeout* is a positive number, it blocks at most *timeout* seconds and raises
83 the :exc:`Full` exception if no free slot was available within that time.
84 Otherwise (*block* is false), put an item on the queue if a free slot is
85 immediately available, else raise the :exc:`Full` exception (*timeout* is
86 ignored in that case).
87
Georg Brandl116aa622007-08-15 14:28:22 +000088
89.. method:: Queue.put_nowait(item)
90
91 Equivalent to ``put(item, False)``.
92
93
94.. method:: Queue.get([block[, timeout]])
95
96 Remove and return an item from the queue. If optional args *block* is true and
97 *timeout* is None (the default), block if necessary until an item is available.
98 If *timeout* is a positive number, it blocks at most *timeout* seconds and
99 raises the :exc:`Empty` exception if no item was available within that time.
100 Otherwise (*block* is false), return an item if one is immediately available,
101 else raise the :exc:`Empty` exception (*timeout* is ignored in that case).
102
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104.. method:: Queue.get_nowait()
105
106 Equivalent to ``get(False)``.
107
108Two methods are offered to support tracking whether enqueued tasks have been
109fully processed by daemon consumer threads.
110
111
112.. method:: Queue.task_done()
113
114 Indicate that a formerly enqueued task is complete. Used by queue consumer
115 threads. For each :meth:`get` used to fetch a task, a subsequent call to
116 :meth:`task_done` tells the queue that the processing on the task is complete.
117
118 If a :meth:`join` is currently blocking, it will resume when all items have been
119 processed (meaning that a :meth:`task_done` call was received for every item
120 that had been :meth:`put` into the queue).
121
122 Raises a :exc:`ValueError` if called more times than there were items placed in
123 the queue.
124
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126.. method:: Queue.join()
127
128 Blocks until all items in the queue have been gotten and processed.
129
130 The count of unfinished tasks goes up whenever an item is added to the queue.
131 The count goes down whenever a consumer thread calls :meth:`task_done` to
132 indicate that the item was retrieved and all work on it is complete. When the
133 count of unfinished tasks drops to zero, join() unblocks.
134
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136Example of how to wait for enqueued tasks to be completed::
137
138 def worker():
139 while True:
140 item = q.get()
141 do_work(item)
142 q.task_done()
143
144 q = Queue()
145 for i in range(num_worker_threads):
146 t = Thread(target=worker)
147 t.setDaemon(True)
148 t.start()
149
150 for item in source():
151 q.put(item)
152
153 q.join() # block until all tasks are done
154