blob: ef07957781a474a7f24f494144357caa8a714d5a [file] [log] [blame]
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +00001'''A multi-producer, multi-consumer queue.'''
Guido van Rossum9022fce1992-08-25 12:30:44 +00002
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02003import threading
Raymond Hettinger756b3f32004-01-29 06:37:52 +00004from collections import deque
Raymond Hettinger143f51a2012-01-09 05:32:01 +00005from heapq import heappush, heappop
Victor Stinnerae586492014-09-02 23:18:25 +02006from time import monotonic as time
Antoine Pitrou94e16962018-01-16 00:27:16 +01007try:
8 from _queue import SimpleQueue
9except ImportError:
10 SimpleQueue = None
Martin v. Löwis77ac4292002-10-15 15:11:13 +000011
Antoine Pitrou94e16962018-01-16 00:27:16 +010012__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue', 'SimpleQueue']
Brett Cannonb42bb5a2003-07-01 05:34:27 +000013
Antoine Pitrou94e16962018-01-16 00:27:16 +010014
15try:
16 from _queue import Empty
17except AttributeError:
18 class Empty(Exception):
19 'Exception raised by Queue.get(block=0)/get_nowait().'
20 pass
Tim Petersb8c94172001-01-15 22:53:46 +000021
22class Full(Exception):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000023 'Exception raised by Queue.put(block=0)/put_nowait().'
Tim Petersb8c94172001-01-15 22:53:46 +000024 pass
Guido van Rossum9022fce1992-08-25 12:30:44 +000025
Antoine Pitrou94e16962018-01-16 00:27:16 +010026
Guido van Rossum9022fce1992-08-25 12:30:44 +000027class Queue:
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000028 '''Create a queue object with a given maximum size.
Guido van Rossum9022fce1992-08-25 12:30:44 +000029
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030 If maxsize is <= 0, the queue size is infinite.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000031 '''
32
Thomas Wouters0e3f5912006-08-11 14:57:12 +000033 def __init__(self, maxsize=0):
Raymond Hettingerda3caed2008-01-14 21:39:24 +000034 self.maxsize = maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000035 self._init(maxsize)
Raymond Hettinger75404272012-01-07 15:32:52 -080036
Tim Peters5af0e412004-07-12 00:45:14 +000037 # mutex must be held whenever the queue is mutating. All methods
38 # that acquire mutex must release it before returning. mutex
Thomas Wouters89f507f2006-12-13 04:49:30 +000039 # is shared between the three conditions, so acquiring and
Tim Peters5af0e412004-07-12 00:45:14 +000040 # releasing the conditions also acquires and releases mutex.
Raymond Hettinger143f51a2012-01-09 05:32:01 +000041 self.mutex = threading.Lock()
Raymond Hettinger75404272012-01-07 15:32:52 -080042
Tim Peters5af0e412004-07-12 00:45:14 +000043 # Notify not_empty whenever an item is added to the queue; a
44 # thread waiting to get is notified then.
Raymond Hettinger143f51a2012-01-09 05:32:01 +000045 self.not_empty = threading.Condition(self.mutex)
Raymond Hettinger75404272012-01-07 15:32:52 -080046
Tim Peters5af0e412004-07-12 00:45:14 +000047 # Notify not_full whenever an item is removed from the queue;
48 # a thread waiting to put is notified then.
Raymond Hettinger143f51a2012-01-09 05:32:01 +000049 self.not_full = threading.Condition(self.mutex)
Raymond Hettinger75404272012-01-07 15:32:52 -080050
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000051 # Notify all_tasks_done whenever the number of unfinished tasks
52 # drops to zero; thread waiting to join() is notified to resume
Raymond Hettinger143f51a2012-01-09 05:32:01 +000053 self.all_tasks_done = threading.Condition(self.mutex)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000054 self.unfinished_tasks = 0
55
56 def task_done(self):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000057 '''Indicate that a formerly enqueued task is complete.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058
59 Used by Queue consumer threads. For each get() used to fetch a task,
60 a subsequent call to task_done() tells the queue that the processing
61 on the task is complete.
62
63 If a join() is currently blocking, it will resume when all items
64 have been processed (meaning that a task_done() call was received
65 for every item that had been put() into the queue).
66
67 Raises a ValueError if called more times than there were items
68 placed in the queue.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000069 '''
Raymond Hettinger75404272012-01-07 15:32:52 -080070 with self.all_tasks_done:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000071 unfinished = self.unfinished_tasks - 1
72 if unfinished <= 0:
73 if unfinished < 0:
74 raise ValueError('task_done() called too many times')
Benjamin Peterson672b8032008-06-11 19:14:14 +000075 self.all_tasks_done.notify_all()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076 self.unfinished_tasks = unfinished
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077
78 def join(self):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000079 '''Blocks until all items in the Queue have been gotten and processed.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000080
81 The count of unfinished tasks goes up whenever an item is added to the
82 queue. The count goes down whenever a consumer thread calls task_done()
83 to indicate the item was retrieved and all work on it is complete.
84
85 When the count of unfinished tasks drops to zero, join() unblocks.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000086 '''
Raymond Hettinger75404272012-01-07 15:32:52 -080087 with self.all_tasks_done:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088 while self.unfinished_tasks:
89 self.all_tasks_done.wait()
Guido van Rossum9022fce1992-08-25 12:30:44 +000090
Barry Warsaw3d96d521997-11-20 19:56:38 +000091 def qsize(self):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000092 '''Return the approximate size of the queue (not reliable!).'''
Raymond Hettinger75404272012-01-07 15:32:52 -080093 with self.mutex:
94 return self._qsize()
Barry Warsaw3d96d521997-11-20 19:56:38 +000095
Alexandre Vassalottif260e442008-05-11 19:59:59 +000096 def empty(self):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +000097 '''Return True if the queue is empty, False otherwise (not reliable!).
Raymond Hettinger611eaf02009-03-06 23:55:28 +000098
99 This method is likely to be removed at some point. Use qsize() == 0
100 as a direct substitute, but be aware that either approach risks a race
101 condition where a queue can grow before the result of empty() or
102 qsize() can be used.
103
104 To create code that needs to wait for all queued tasks to be
105 completed, the preferred technique is to use the join() method.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000106 '''
Raymond Hettinger75404272012-01-07 15:32:52 -0800107 with self.mutex:
108 return not self._qsize()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000109
110 def full(self):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000111 '''Return True if the queue is full, False otherwise (not reliable!).
Raymond Hettinger611eaf02009-03-06 23:55:28 +0000112
Raymond Hettinger189316a2010-10-31 17:57:52 +0000113 This method is likely to be removed at some point. Use qsize() >= n
Raymond Hettinger611eaf02009-03-06 23:55:28 +0000114 as a direct substitute, but be aware that either approach risks a race
115 condition where a queue can shrink before the result of full() or
116 qsize() can be used.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000117 '''
Raymond Hettinger75404272012-01-07 15:32:52 -0800118 with self.mutex:
119 return 0 < self.maxsize <= self._qsize()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000120
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000121 def put(self, item, block=True, timeout=None):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000122 '''Put an item into the queue.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000123
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000124 If optional args 'block' is true and 'timeout' is None (the default),
125 block if necessary until a free slot is available. If 'timeout' is
Terry Jan Reedy7608b602013-08-10 18:17:13 -0400126 a non-negative number, it blocks at most 'timeout' seconds and raises
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000127 the Full exception if no free slot was available within that time.
128 Otherwise ('block' is false), put an item on the queue if a free slot
129 is immediately available, else raise the Full exception ('timeout'
130 is ignored in that case).
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000131 '''
Raymond Hettinger75404272012-01-07 15:32:52 -0800132 with self.not_full:
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000133 if self.maxsize > 0:
134 if not block:
Raymond Hettinger189316a2010-10-31 17:57:52 +0000135 if self._qsize() >= self.maxsize:
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000136 raise Full
137 elif timeout is None:
Raymond Hettinger189316a2010-10-31 17:57:52 +0000138 while self._qsize() >= self.maxsize:
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000139 self.not_full.wait()
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000140 elif timeout < 0:
Terry Jan Reedy7608b602013-08-10 18:17:13 -0400141 raise ValueError("'timeout' must be a non-negative number")
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000142 else:
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000143 endtime = time() + timeout
Raymond Hettinger189316a2010-10-31 17:57:52 +0000144 while self._qsize() >= self.maxsize:
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000145 remaining = endtime - time()
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000146 if remaining <= 0.0:
147 raise Full
148 self.not_full.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000149 self._put(item)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000150 self.unfinished_tasks += 1
Tim Peters5af0e412004-07-12 00:45:14 +0000151 self.not_empty.notify()
Barry Warsaw3d96d521997-11-20 19:56:38 +0000152
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000153 def get(self, block=True, timeout=None):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000154 '''Remove and return an item from the queue.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000155
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000156 If optional args 'block' is true and 'timeout' is None (the default),
157 block if necessary until an item is available. If 'timeout' is
Terry Jan Reedy7608b602013-08-10 18:17:13 -0400158 a non-negative number, it blocks at most 'timeout' seconds and raises
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000159 the Empty exception if no item was available within that time.
160 Otherwise ('block' is false), return an item if one is immediately
161 available, else raise the Empty exception ('timeout' is ignored
162 in that case).
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000163 '''
Raymond Hettinger75404272012-01-07 15:32:52 -0800164 with self.not_empty:
Tim Peters71ed2202004-07-12 01:20:32 +0000165 if not block:
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000166 if not self._qsize():
Tim Peters71ed2202004-07-12 01:20:32 +0000167 raise Empty
168 elif timeout is None:
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000169 while not self._qsize():
Tim Peters5af0e412004-07-12 00:45:14 +0000170 self.not_empty.wait()
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000171 elif timeout < 0:
Terry Jan Reedy7608b602013-08-10 18:17:13 -0400172 raise ValueError("'timeout' must be a non-negative number")
Tim Peters5af0e412004-07-12 00:45:14 +0000173 else:
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000174 endtime = time() + timeout
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000175 while not self._qsize():
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000176 remaining = endtime - time()
Tim Peters71ed2202004-07-12 01:20:32 +0000177 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +0000178 raise Empty
179 self.not_empty.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000180 item = self._get()
Tim Peters5af0e412004-07-12 00:45:14 +0000181 self.not_full.notify()
182 return item
Guido van Rossum9022fce1992-08-25 12:30:44 +0000183
Raymond Hettinger61bd7292012-01-09 06:02:08 +0000184 def put_nowait(self, item):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000185 '''Put an item into the queue without blocking.
Raymond Hettinger61bd7292012-01-09 06:02:08 +0000186
187 Only enqueue the item if a free slot is immediately available.
188 Otherwise raise the Full exception.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000189 '''
Raymond Hettinger61bd7292012-01-09 06:02:08 +0000190 return self.put(item, block=False)
191
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000192 def get_nowait(self):
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000193 '''Remove and return an item from the queue without blocking.
Guido van Rossum9022fce1992-08-25 12:30:44 +0000194
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000195 Only get an item if one is immediately available. Otherwise
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000196 raise the Empty exception.
Raymond Hettinger0c5e52f2012-01-09 06:17:39 +0000197 '''
Raymond Hettinger61bd7292012-01-09 06:02:08 +0000198 return self.get(block=False)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000199
Barry Warsaw3d96d521997-11-20 19:56:38 +0000200 # Override these methods to implement other queue organizations
201 # (e.g. stack or priority queue).
202 # These will only be called with appropriate locks held
Guido van Rossum9022fce1992-08-25 12:30:44 +0000203
Barry Warsaw3d96d521997-11-20 19:56:38 +0000204 # Initialize the queue representation
205 def _init(self, maxsize):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000206 self.queue = deque()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000207
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000208 def _qsize(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000209 return len(self.queue)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000210
Barry Warsaw3d96d521997-11-20 19:56:38 +0000211 # Put a new item in the queue
212 def _put(self, item):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 self.queue.append(item)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000214
Barry Warsaw3d96d521997-11-20 19:56:38 +0000215 # Get an item from the queue
216 def _get(self):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000217 return self.queue.popleft()
Raymond Hettinger35641462008-01-17 00:13:27 +0000218
219
220class PriorityQueue(Queue):
221 '''Variant of Queue that retrieves open entries in priority order (lowest first).
222
223 Entries are typically tuples of the form: (priority number, data).
224 '''
225
226 def _init(self, maxsize):
227 self.queue = []
228
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000229 def _qsize(self):
Raymond Hettinger35641462008-01-17 00:13:27 +0000230 return len(self.queue)
231
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000232 def _put(self, item):
Raymond Hettinger35641462008-01-17 00:13:27 +0000233 heappush(self.queue, item)
234
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000235 def _get(self):
Raymond Hettinger35641462008-01-17 00:13:27 +0000236 return heappop(self.queue)
237
238
239class LifoQueue(Queue):
240 '''Variant of Queue that retrieves most recently added entries first.'''
241
242 def _init(self, maxsize):
243 self.queue = []
244
Raymond Hettinger143f51a2012-01-09 05:32:01 +0000245 def _qsize(self):
Raymond Hettinger35641462008-01-17 00:13:27 +0000246 return len(self.queue)
247
248 def _put(self, item):
249 self.queue.append(item)
250
251 def _get(self):
252 return self.queue.pop()
Antoine Pitrou94e16962018-01-16 00:27:16 +0100253
254
255class _PySimpleQueue:
256 '''Simple, unbounded FIFO queue.
257
258 This pure Python implementation is not reentrant.
259 '''
260 # Note: while this pure Python version provides fairness
261 # (by using a threading.Semaphore which is itself fair, being based
262 # on threading.Condition), fairness is not part of the API contract.
263 # This allows the C version to use a different implementation.
264
265 def __init__(self):
266 self._queue = deque()
267 self._count = threading.Semaphore(0)
268
269 def put(self, item, block=True, timeout=None):
270 '''Put the item on the queue.
271
272 The optional 'block' and 'timeout' arguments are ignored, as this method
273 never blocks. They are provided for compatibility with the Queue class.
274 '''
275 self._queue.append(item)
276 self._count.release()
277
278 def get(self, block=True, timeout=None):
279 '''Remove and return an item from the queue.
280
281 If optional args 'block' is true and 'timeout' is None (the default),
282 block if necessary until an item is available. If 'timeout' is
283 a non-negative number, it blocks at most 'timeout' seconds and raises
284 the Empty exception if no item was available within that time.
285 Otherwise ('block' is false), return an item if one is immediately
286 available, else raise the Empty exception ('timeout' is ignored
287 in that case).
288 '''
289 if timeout is not None and timeout < 0:
290 raise ValueError("'timeout' must be a non-negative number")
291 if not self._count.acquire(block, timeout):
292 raise Empty
293 return self._queue.popleft()
294
295 def put_nowait(self, item):
296 '''Put an item into the queue without blocking.
297
298 This is exactly equivalent to `put(item)` and is only provided
299 for compatibility with the Queue class.
300 '''
301 return self.put(item, block=False)
302
303 def get_nowait(self):
304 '''Remove and return an item from the queue without blocking.
305
306 Only get an item if one is immediately available. Otherwise
307 raise the Empty exception.
308 '''
309 return self.get(block=False)
310
311 def empty(self):
312 '''Return True if the queue is empty, False otherwise (not reliable!).'''
313 return len(self._queue) == 0
314
315 def qsize(self):
316 '''Return the approximate size of the queue (not reliable!).'''
317 return len(self._queue)
318
319
320if SimpleQueue is None:
321 SimpleQueue = _PySimpleQueue