queue.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # util/queue.py
  2. # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """An adaptation of Py2.3/2.4's Queue module which supports reentrant
  8. behavior, using RLock instead of Lock for its mutex object. The
  9. Queue object is used exclusively by the sqlalchemy.pool.QueuePool
  10. class.
  11. This is to support the connection pool's usage of weakref callbacks to return
  12. connections to the underlying Queue, which can in extremely
  13. rare cases be invoked within the ``get()`` method of the Queue itself,
  14. producing a ``put()`` inside the ``get()`` and therefore a reentrant
  15. condition.
  16. """
  17. from collections import deque
  18. from time import time as _time
  19. from . import compat
  20. from .compat import threading
  21. from .concurrency import asyncio
  22. from .concurrency import await_fallback
  23. from .concurrency import await_only
  24. from .langhelpers import memoized_property
  25. __all__ = ["Empty", "Full", "Queue"]
  26. class Empty(Exception):
  27. "Exception raised by Queue.get(block=0)/get_nowait()."
  28. pass
  29. class Full(Exception):
  30. "Exception raised by Queue.put(block=0)/put_nowait()."
  31. pass
  32. class Queue:
  33. def __init__(self, maxsize=0, use_lifo=False):
  34. """Initialize a queue object with a given maximum size.
  35. If `maxsize` is <= 0, the queue size is infinite.
  36. If `use_lifo` is True, this Queue acts like a Stack (LIFO).
  37. """
  38. self._init(maxsize)
  39. # mutex must be held whenever the queue is mutating. All methods
  40. # that acquire mutex must release it before returning. mutex
  41. # is shared between the two conditions, so acquiring and
  42. # releasing the conditions also acquires and releases mutex.
  43. self.mutex = threading.RLock()
  44. # Notify not_empty whenever an item is added to the queue; a
  45. # thread waiting to get is notified then.
  46. self.not_empty = threading.Condition(self.mutex)
  47. # Notify not_full whenever an item is removed from the queue;
  48. # a thread waiting to put is notified then.
  49. self.not_full = threading.Condition(self.mutex)
  50. # If this queue uses LIFO or FIFO
  51. self.use_lifo = use_lifo
  52. def qsize(self):
  53. """Return the approximate size of the queue (not reliable!)."""
  54. with self.mutex:
  55. return self._qsize()
  56. def empty(self):
  57. """Return True if the queue is empty, False otherwise (not
  58. reliable!)."""
  59. with self.mutex:
  60. return self._empty()
  61. def full(self):
  62. """Return True if the queue is full, False otherwise (not
  63. reliable!)."""
  64. with self.mutex:
  65. return self._full()
  66. def put(self, item, block=True, timeout=None):
  67. """Put an item into the queue.
  68. If optional args `block` is True and `timeout` is None (the
  69. default), block if necessary until a free slot is
  70. available. If `timeout` is a positive number, it blocks at
  71. most `timeout` seconds and raises the ``Full`` exception if no
  72. free slot was available within that time. Otherwise (`block`
  73. is false), put an item on the queue if a free slot is
  74. immediately available, else raise the ``Full`` exception
  75. (`timeout` is ignored in that case).
  76. """
  77. with self.not_full:
  78. if not block:
  79. if self._full():
  80. raise Full
  81. elif timeout is None:
  82. while self._full():
  83. self.not_full.wait()
  84. else:
  85. if timeout < 0:
  86. raise ValueError("'timeout' must be a positive number")
  87. endtime = _time() + timeout
  88. while self._full():
  89. remaining = endtime - _time()
  90. if remaining <= 0.0:
  91. raise Full
  92. self.not_full.wait(remaining)
  93. self._put(item)
  94. self.not_empty.notify()
  95. def put_nowait(self, item):
  96. """Put an item into the queue without blocking.
  97. Only enqueue the item if a free slot is immediately available.
  98. Otherwise raise the ``Full`` exception.
  99. """
  100. return self.put(item, False)
  101. def get(self, block=True, timeout=None):
  102. """Remove and return an item from the queue.
  103. If optional args `block` is True and `timeout` is None (the
  104. default), block if necessary until an item is available. If
  105. `timeout` is a positive number, it blocks at most `timeout`
  106. seconds and raises the ``Empty`` exception if no item was
  107. available within that time. Otherwise (`block` is false),
  108. return an item if one is immediately available, else raise the
  109. ``Empty`` exception (`timeout` is ignored in that case).
  110. """
  111. with self.not_empty:
  112. if not block:
  113. if self._empty():
  114. raise Empty
  115. elif timeout is None:
  116. while self._empty():
  117. self.not_empty.wait()
  118. else:
  119. if timeout < 0:
  120. raise ValueError("'timeout' must be a positive number")
  121. endtime = _time() + timeout
  122. while self._empty():
  123. remaining = endtime - _time()
  124. if remaining <= 0.0:
  125. raise Empty
  126. self.not_empty.wait(remaining)
  127. item = self._get()
  128. self.not_full.notify()
  129. return item
  130. def get_nowait(self):
  131. """Remove and return an item from the queue without blocking.
  132. Only get an item if one is immediately available. Otherwise
  133. raise the ``Empty`` exception.
  134. """
  135. return self.get(False)
  136. # Override these methods to implement other queue organizations
  137. # (e.g. stack or priority queue).
  138. # These will only be called with appropriate locks held
  139. # Initialize the queue representation
  140. def _init(self, maxsize):
  141. self.maxsize = maxsize
  142. self.queue = deque()
  143. def _qsize(self):
  144. return len(self.queue)
  145. # Check whether the queue is empty
  146. def _empty(self):
  147. return not self.queue
  148. # Check whether the queue is full
  149. def _full(self):
  150. return self.maxsize > 0 and len(self.queue) == self.maxsize
  151. # Put a new item in the queue
  152. def _put(self, item):
  153. self.queue.append(item)
  154. # Get an item from the queue
  155. def _get(self):
  156. if self.use_lifo:
  157. # LIFO
  158. return self.queue.pop()
  159. else:
  160. # FIFO
  161. return self.queue.popleft()
  162. class AsyncAdaptedQueue:
  163. await_ = staticmethod(await_only)
  164. def __init__(self, maxsize=0, use_lifo=False):
  165. self.use_lifo = use_lifo
  166. self.maxsize = maxsize
  167. def empty(self):
  168. return self._queue.empty()
  169. def full(self):
  170. return self._queue.full()
  171. def qsize(self):
  172. return self._queue.qsize()
  173. @memoized_property
  174. def _queue(self):
  175. # Delay creation of the queue until it is first used, to avoid
  176. # binding it to a possibly wrong event loop.
  177. # By delaying the creation of the pool we accommodate the common
  178. # usage pattern of instantiating the engine at module level, where a
  179. # different event loop is in present compared to when the application
  180. # is actually run.
  181. if self.use_lifo:
  182. queue = asyncio.LifoQueue(maxsize=self.maxsize)
  183. else:
  184. queue = asyncio.Queue(maxsize=self.maxsize)
  185. return queue
  186. def put_nowait(self, item):
  187. try:
  188. return self._queue.put_nowait(item)
  189. except asyncio.QueueFull as err:
  190. compat.raise_(
  191. Full(),
  192. replace_context=err,
  193. )
  194. def put(self, item, block=True, timeout=None):
  195. if not block:
  196. return self.put_nowait(item)
  197. try:
  198. if timeout is not None:
  199. return self.await_(
  200. asyncio.wait_for(self._queue.put(item), timeout)
  201. )
  202. else:
  203. return self.await_(self._queue.put(item))
  204. except (asyncio.QueueFull, asyncio.TimeoutError) as err:
  205. compat.raise_(
  206. Full(),
  207. replace_context=err,
  208. )
  209. def get_nowait(self):
  210. try:
  211. return self._queue.get_nowait()
  212. except asyncio.QueueEmpty as err:
  213. compat.raise_(
  214. Empty(),
  215. replace_context=err,
  216. )
  217. def get(self, block=True, timeout=None):
  218. if not block:
  219. return self.get_nowait()
  220. try:
  221. if timeout is not None:
  222. return self.await_(
  223. asyncio.wait_for(self._queue.get(), timeout)
  224. )
  225. else:
  226. return self.await_(self._queue.get())
  227. except (asyncio.QueueEmpty, asyncio.TimeoutError) as err:
  228. compat.raise_(
  229. Empty(),
  230. replace_context=err,
  231. )
  232. class FallbackAsyncAdaptedQueue(AsyncAdaptedQueue):
  233. await_ = staticmethod(await_fallback)