queues.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. __all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty')
  2. import collections
  3. import heapq
  4. import warnings
  5. from types import GenericAlias
  6. from . import events
  7. from . import locks
  8. class QueueEmpty(Exception):
  9. """Raised when Queue.get_nowait() is called on an empty Queue."""
  10. pass
  11. class QueueFull(Exception):
  12. """Raised when the Queue.put_nowait() method is called on a full Queue."""
  13. pass
  14. class Queue:
  15. """A queue, useful for coordinating producer and consumer coroutines.
  16. If maxsize is less than or equal to zero, the queue size is infinite. If it
  17. is an integer greater than 0, then "await put()" will block when the
  18. queue reaches maxsize, until an item is removed by get().
  19. Unlike the standard library Queue, you can reliably know this Queue's size
  20. with qsize(), since your single-threaded asyncio application won't be
  21. interrupted between calling qsize() and doing an operation on the Queue.
  22. """
  23. def __init__(self, maxsize=0, *, loop=None):
  24. if loop is None:
  25. self._loop = events.get_event_loop()
  26. else:
  27. self._loop = loop
  28. warnings.warn("The loop argument is deprecated since Python 3.8, "
  29. "and scheduled for removal in Python 3.10.",
  30. DeprecationWarning, stacklevel=2)
  31. self._maxsize = maxsize
  32. # Futures.
  33. self._getters = collections.deque()
  34. # Futures.
  35. self._putters = collections.deque()
  36. self._unfinished_tasks = 0
  37. self._finished = locks.Event(loop=loop)
  38. self._finished.set()
  39. self._init(maxsize)
  40. # These three are overridable in subclasses.
  41. def _init(self, maxsize):
  42. self._queue = collections.deque()
  43. def _get(self):
  44. return self._queue.popleft()
  45. def _put(self, item):
  46. self._queue.append(item)
  47. # End of the overridable methods.
  48. def _wakeup_next(self, waiters):
  49. # Wake up the next waiter (if any) that isn't cancelled.
  50. while waiters:
  51. waiter = waiters.popleft()
  52. if not waiter.done():
  53. waiter.set_result(None)
  54. break
  55. def __repr__(self):
  56. return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'
  57. def __str__(self):
  58. return f'<{type(self).__name__} {self._format()}>'
  59. __class_getitem__ = classmethod(GenericAlias)
  60. def _format(self):
  61. result = f'maxsize={self._maxsize!r}'
  62. if getattr(self, '_queue', None):
  63. result += f' _queue={list(self._queue)!r}'
  64. if self._getters:
  65. result += f' _getters[{len(self._getters)}]'
  66. if self._putters:
  67. result += f' _putters[{len(self._putters)}]'
  68. if self._unfinished_tasks:
  69. result += f' tasks={self._unfinished_tasks}'
  70. return result
  71. def qsize(self):
  72. """Number of items in the queue."""
  73. return len(self._queue)
  74. @property
  75. def maxsize(self):
  76. """Number of items allowed in the queue."""
  77. return self._maxsize
  78. def empty(self):
  79. """Return True if the queue is empty, False otherwise."""
  80. return not self._queue
  81. def full(self):
  82. """Return True if there are maxsize items in the queue.
  83. Note: if the Queue was initialized with maxsize=0 (the default),
  84. then full() is never True.
  85. """
  86. if self._maxsize <= 0:
  87. return False
  88. else:
  89. return self.qsize() >= self._maxsize
  90. async def put(self, item):
  91. """Put an item into the queue.
  92. Put an item into the queue. If the queue is full, wait until a free
  93. slot is available before adding item.
  94. """
  95. while self.full():
  96. putter = self._loop.create_future()
  97. self._putters.append(putter)
  98. try:
  99. await putter
  100. except:
  101. putter.cancel() # Just in case putter is not done yet.
  102. try:
  103. # Clean self._putters from canceled putters.
  104. self._putters.remove(putter)
  105. except ValueError:
  106. # The putter could be removed from self._putters by a
  107. # previous get_nowait call.
  108. pass
  109. if not self.full() and not putter.cancelled():
  110. # We were woken up by get_nowait(), but can't take
  111. # the call. Wake up the next in line.
  112. self._wakeup_next(self._putters)
  113. raise
  114. return self.put_nowait(item)
  115. def put_nowait(self, item):
  116. """Put an item into the queue without blocking.
  117. If no free slot is immediately available, raise QueueFull.
  118. """
  119. if self.full():
  120. raise QueueFull
  121. self._put(item)
  122. self._unfinished_tasks += 1
  123. self._finished.clear()
  124. self._wakeup_next(self._getters)
  125. async def get(self):
  126. """Remove and return an item from the queue.
  127. If queue is empty, wait until an item is available.
  128. """
  129. while self.empty():
  130. getter = self._loop.create_future()
  131. self._getters.append(getter)
  132. try:
  133. await getter
  134. except:
  135. getter.cancel() # Just in case getter is not done yet.
  136. try:
  137. # Clean self._getters from canceled getters.
  138. self._getters.remove(getter)
  139. except ValueError:
  140. # The getter could be removed from self._getters by a
  141. # previous put_nowait call.
  142. pass
  143. if not self.empty() and not getter.cancelled():
  144. # We were woken up by put_nowait(), but can't take
  145. # the call. Wake up the next in line.
  146. self._wakeup_next(self._getters)
  147. raise
  148. return self.get_nowait()
  149. def get_nowait(self):
  150. """Remove and return an item from the queue.
  151. Return an item if one is immediately available, else raise QueueEmpty.
  152. """
  153. if self.empty():
  154. raise QueueEmpty
  155. item = self._get()
  156. self._wakeup_next(self._putters)
  157. return item
  158. def task_done(self):
  159. """Indicate that a formerly enqueued task is complete.
  160. Used by queue consumers. For each get() used to fetch a task,
  161. a subsequent call to task_done() tells the queue that the processing
  162. on the task is complete.
  163. If a join() is currently blocking, it will resume when all items have
  164. been processed (meaning that a task_done() call was received for every
  165. item that had been put() into the queue).
  166. Raises ValueError if called more times than there were items placed in
  167. the queue.
  168. """
  169. if self._unfinished_tasks <= 0:
  170. raise ValueError('task_done() called too many times')
  171. self._unfinished_tasks -= 1
  172. if self._unfinished_tasks == 0:
  173. self._finished.set()
  174. async def join(self):
  175. """Block until all items in the queue have been gotten and processed.
  176. The count of unfinished tasks goes up whenever an item is added to the
  177. queue. The count goes down whenever a consumer calls task_done() to
  178. indicate that the item was retrieved and all work on it is complete.
  179. When the count of unfinished tasks drops to zero, join() unblocks.
  180. """
  181. if self._unfinished_tasks > 0:
  182. await self._finished.wait()
  183. class PriorityQueue(Queue):
  184. """A subclass of Queue; retrieves entries in priority order (lowest first).
  185. Entries are typically tuples of the form: (priority number, data).
  186. """
  187. def _init(self, maxsize):
  188. self._queue = []
  189. def _put(self, item, heappush=heapq.heappush):
  190. heappush(self._queue, item)
  191. def _get(self, heappop=heapq.heappop):
  192. return heappop(self._queue)
  193. class LifoQueue(Queue):
  194. """A subclass of Queue that retrieves most recently added entries first."""
  195. def _init(self, maxsize):
  196. self._queue = []
  197. def _put(self, item):
  198. self._queue.append(item)
  199. def _get(self):
  200. return self._queue.pop()