queues.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # Copyright 2015 The Tornado Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  4. # not use this file except in compliance with the License. You may obtain
  5. # a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. from __future__ import absolute_import, division, print_function, with_statement
  15. __all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty']
  16. import collections
  17. import heapq
  18. from tornado import gen, ioloop
  19. from tornado.concurrent import Future
  20. from tornado.locks import Event
  21. class QueueEmpty(Exception):
  22. """Raised by `.Queue.get_nowait` when the queue has no items."""
  23. pass
  24. class QueueFull(Exception):
  25. """Raised by `.Queue.put_nowait` when a queue is at its maximum size."""
  26. pass
  27. def _set_timeout(future, timeout):
  28. if timeout:
  29. def on_timeout():
  30. future.set_exception(gen.TimeoutError())
  31. io_loop = ioloop.IOLoop.current()
  32. timeout_handle = io_loop.add_timeout(timeout, on_timeout)
  33. future.add_done_callback(
  34. lambda _: io_loop.remove_timeout(timeout_handle))
  35. class _QueueIterator(object):
  36. def __init__(self, q):
  37. self.q = q
  38. def __anext__(self):
  39. return self.q.get()
  40. class Queue(object):
  41. """Coordinate producer and consumer coroutines.
  42. If maxsize is 0 (the default) the queue size is unbounded.
  43. .. testcode::
  44. from tornado import gen
  45. from tornado.ioloop import IOLoop
  46. from tornado.queues import Queue
  47. q = Queue(maxsize=2)
  48. @gen.coroutine
  49. def consumer():
  50. while True:
  51. item = yield q.get()
  52. try:
  53. print('Doing work on %s' % item)
  54. yield gen.sleep(0.01)
  55. finally:
  56. q.task_done()
  57. @gen.coroutine
  58. def producer():
  59. for item in range(5):
  60. yield q.put(item)
  61. print('Put %s' % item)
  62. @gen.coroutine
  63. def main():
  64. # Start consumer without waiting (since it never finishes).
  65. IOLoop.current().spawn_callback(consumer)
  66. yield producer() # Wait for producer to put all tasks.
  67. yield q.join() # Wait for consumer to finish all tasks.
  68. print('Done')
  69. IOLoop.current().run_sync(main)
  70. .. testoutput::
  71. Put 0
  72. Put 1
  73. Doing work on 0
  74. Put 2
  75. Doing work on 1
  76. Put 3
  77. Doing work on 2
  78. Put 4
  79. Doing work on 3
  80. Doing work on 4
  81. Done
  82. In Python 3.5, `Queue` implements the async iterator protocol, so
  83. ``consumer()`` could be rewritten as::
  84. async def consumer():
  85. async for item in q:
  86. try:
  87. print('Doing work on %s' % item)
  88. yield gen.sleep(0.01)
  89. finally:
  90. q.task_done()
  91. .. versionchanged:: 4.3
  92. Added ``async for`` support in Python 3.5.
  93. """
  94. def __init__(self, maxsize=0):
  95. if maxsize is None:
  96. raise TypeError("maxsize can't be None")
  97. if maxsize < 0:
  98. raise ValueError("maxsize can't be negative")
  99. self._maxsize = maxsize
  100. self._init()
  101. self._getters = collections.deque([]) # Futures.
  102. self._putters = collections.deque([]) # Pairs of (item, Future).
  103. self._unfinished_tasks = 0
  104. self._finished = Event()
  105. self._finished.set()
  106. @property
  107. def maxsize(self):
  108. """Number of items allowed in the queue."""
  109. return self._maxsize
  110. def qsize(self):
  111. """Number of items in the queue."""
  112. return len(self._queue)
  113. def empty(self):
  114. return not self._queue
  115. def full(self):
  116. if self.maxsize == 0:
  117. return False
  118. else:
  119. return self.qsize() >= self.maxsize
  120. def put(self, item, timeout=None):
  121. """Put an item into the queue, perhaps waiting until there is room.
  122. Returns a Future, which raises `tornado.gen.TimeoutError` after a
  123. timeout.
  124. """
  125. try:
  126. self.put_nowait(item)
  127. except QueueFull:
  128. future = Future()
  129. self._putters.append((item, future))
  130. _set_timeout(future, timeout)
  131. return future
  132. else:
  133. return gen._null_future
  134. def put_nowait(self, item):
  135. """Put an item into the queue without blocking.
  136. If no free slot is immediately available, raise `QueueFull`.
  137. """
  138. self._consume_expired()
  139. if self._getters:
  140. assert self.empty(), "queue non-empty, why are getters waiting?"
  141. getter = self._getters.popleft()
  142. self.__put_internal(item)
  143. getter.set_result(self._get())
  144. elif self.full():
  145. raise QueueFull
  146. else:
  147. self.__put_internal(item)
  148. def get(self, timeout=None):
  149. """Remove and return an item from the queue.
  150. Returns a Future which resolves once an item is available, or raises
  151. `tornado.gen.TimeoutError` after a timeout.
  152. """
  153. future = Future()
  154. try:
  155. future.set_result(self.get_nowait())
  156. except QueueEmpty:
  157. self._getters.append(future)
  158. _set_timeout(future, timeout)
  159. return future
  160. def get_nowait(self):
  161. """Remove and return an item from the queue without blocking.
  162. Return an item if one is immediately available, else raise
  163. `QueueEmpty`.
  164. """
  165. self._consume_expired()
  166. if self._putters:
  167. assert self.full(), "queue not full, why are putters waiting?"
  168. item, putter = self._putters.popleft()
  169. self.__put_internal(item)
  170. putter.set_result(None)
  171. return self._get()
  172. elif self.qsize():
  173. return self._get()
  174. else:
  175. raise QueueEmpty
  176. def task_done(self):
  177. """Indicate that a formerly enqueued task is complete.
  178. Used by queue consumers. For each `.get` used to fetch a task, a
  179. subsequent call to `.task_done` tells the queue that the processing
  180. on the task is complete.
  181. If a `.join` is blocking, it resumes when all items have been
  182. processed; that is, when every `.put` is matched by a `.task_done`.
  183. Raises `ValueError` if called more times than `.put`.
  184. """
  185. if self._unfinished_tasks <= 0:
  186. raise ValueError('task_done() called too many times')
  187. self._unfinished_tasks -= 1
  188. if self._unfinished_tasks == 0:
  189. self._finished.set()
  190. def join(self, timeout=None):
  191. """Block until all items in the queue are processed.
  192. Returns a Future, which raises `tornado.gen.TimeoutError` after a
  193. timeout.
  194. """
  195. return self._finished.wait(timeout)
  196. @gen.coroutine
  197. def __aiter__(self):
  198. return _QueueIterator(self)
  199. # These three are overridable in subclasses.
  200. def _init(self):
  201. self._queue = collections.deque()
  202. def _get(self):
  203. return self._queue.popleft()
  204. def _put(self, item):
  205. self._queue.append(item)
  206. # End of the overridable methods.
  207. def __put_internal(self, item):
  208. self._unfinished_tasks += 1
  209. self._finished.clear()
  210. self._put(item)
  211. def _consume_expired(self):
  212. # Remove timed-out waiters.
  213. while self._putters and self._putters[0][1].done():
  214. self._putters.popleft()
  215. while self._getters and self._getters[0].done():
  216. self._getters.popleft()
  217. def __repr__(self):
  218. return '<%s at %s %s>' % (
  219. type(self).__name__, hex(id(self)), self._format())
  220. def __str__(self):
  221. return '<%s %s>' % (type(self).__name__, self._format())
  222. def _format(self):
  223. result = 'maxsize=%r' % (self.maxsize, )
  224. if getattr(self, '_queue', None):
  225. result += ' queue=%r' % self._queue
  226. if self._getters:
  227. result += ' getters[%s]' % len(self._getters)
  228. if self._putters:
  229. result += ' putters[%s]' % len(self._putters)
  230. if self._unfinished_tasks:
  231. result += ' tasks=%s' % self._unfinished_tasks
  232. return result
  233. class PriorityQueue(Queue):
  234. """A `.Queue` that retrieves entries in priority order, lowest first.
  235. Entries are typically tuples like ``(priority number, data)``.
  236. .. testcode::
  237. from tornado.queues import PriorityQueue
  238. q = PriorityQueue()
  239. q.put((1, 'medium-priority item'))
  240. q.put((0, 'high-priority item'))
  241. q.put((10, 'low-priority item'))
  242. print(q.get_nowait())
  243. print(q.get_nowait())
  244. print(q.get_nowait())
  245. .. testoutput::
  246. (0, 'high-priority item')
  247. (1, 'medium-priority item')
  248. (10, 'low-priority item')
  249. """
  250. def _init(self):
  251. self._queue = []
  252. def _put(self, item):
  253. heapq.heappush(self._queue, item)
  254. def _get(self):
  255. return heapq.heappop(self._queue)
  256. class LifoQueue(Queue):
  257. """A `.Queue` that retrieves the most recently put items first.
  258. .. testcode::
  259. from tornado.queues import LifoQueue
  260. q = LifoQueue()
  261. q.put(3)
  262. q.put(2)
  263. q.put(1)
  264. print(q.get_nowait())
  265. print(q.get_nowait())
  266. print(q.get_nowait())
  267. .. testoutput::
  268. 1
  269. 2
  270. 3
  271. """
  272. def _init(self):
  273. self._queue = []
  274. def _put(self, item):
  275. self._queue.append(item)
  276. def _get(self):
  277. return self._queue.pop()