queue.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. # Copyright (c) 2009 Denis Bilenko, denis.bilenko at gmail com
  2. # Copyright (c) 2010 Eventlet Contributors (see AUTHORS)
  3. # and licensed under the MIT license:
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. """Synchronized queues.
  23. The :mod:`eventlet.queue` module implements multi-producer, multi-consumer
  24. queues that work across greenlets, with the API similar to the classes found in
  25. the standard :mod:`Queue` and :class:`multiprocessing <multiprocessing.Queue>`
  26. modules.
  27. A major difference is that queues in this module operate as channels when
  28. initialized with *maxsize* of zero. In such case, both :meth:`Queue.empty`
  29. and :meth:`Queue.full` return ``True`` and :meth:`Queue.put` always blocks until
  30. a call to :meth:`Queue.get` retrieves the item.
  31. An interesting difference, made possible because of greenthreads, is
  32. that :meth:`Queue.qsize`, :meth:`Queue.empty`, and :meth:`Queue.full` *can* be
  33. used as indicators of whether the subsequent :meth:`Queue.get`
  34. or :meth:`Queue.put` will not block. The new methods :meth:`Queue.getting`
  35. and :meth:`Queue.putting` report on the number of greenthreads blocking
  36. in :meth:`put <Queue.put>` or :meth:`get <Queue.get>` respectively.
  37. """
  38. import sys
  39. import heapq
  40. import collections
  41. import traceback
  42. from Queue import Full, Empty
  43. _NONE = object()
  44. from eventlet.hubs import get_hub
  45. from eventlet.greenthread import getcurrent
  46. from eventlet.event import Event
  47. from eventlet.timeout import Timeout
  48. __all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'LightQueue', 'Full', 'Empty']
  49. class Waiter(object):
  50. """A low level synchronization class.
  51. Wrapper around greenlet's ``switch()`` and ``throw()`` calls that makes them safe:
  52. * switching will occur only if the waiting greenlet is executing :meth:`wait`
  53. method currently. Otherwise, :meth:`switch` and :meth:`throw` are no-ops.
  54. * any error raised in the greenlet is handled inside :meth:`switch` and :meth:`throw`
  55. The :meth:`switch` and :meth:`throw` methods must only be called from the :class:`Hub` greenlet.
  56. The :meth:`wait` method must be called from a greenlet other than :class:`Hub`.
  57. """
  58. __slots__ = ['greenlet']
  59. def __init__(self):
  60. self.greenlet = None
  61. def __repr__(self):
  62. if self.waiting:
  63. waiting = ' waiting'
  64. else:
  65. waiting = ''
  66. return '<%s at %s%s greenlet=%r>' % (type(self).__name__, hex(id(self)), waiting, self.greenlet)
  67. def __str__(self):
  68. """
  69. >>> print Waiter()
  70. <Waiter greenlet=None>
  71. """
  72. if self.waiting:
  73. waiting = ' waiting'
  74. else:
  75. waiting = ''
  76. return '<%s%s greenlet=%s>' % (type(self).__name__, waiting, self.greenlet)
  77. def __nonzero__(self):
  78. return self.greenlet is not None
  79. @property
  80. def waiting(self):
  81. return self.greenlet is not None
  82. def switch(self, value=None):
  83. """Wake up the greenlet that is calling wait() currently (if there is one).
  84. Can only be called from Hub's greenlet.
  85. """
  86. assert getcurrent() is get_hub().greenlet, "Can only use Waiter.switch method from the mainloop"
  87. if self.greenlet is not None:
  88. try:
  89. self.greenlet.switch(value)
  90. except:
  91. traceback.print_exc()
  92. def throw(self, *throw_args):
  93. """Make greenlet calling wait() wake up (if there is a wait()).
  94. Can only be called from Hub's greenlet.
  95. """
  96. assert getcurrent() is get_hub().greenlet, "Can only use Waiter.switch method from the mainloop"
  97. if self.greenlet is not None:
  98. try:
  99. self.greenlet.throw(*throw_args)
  100. except:
  101. traceback.print_exc()
  102. # XXX should be renamed to get() ? and the whole class is called Receiver?
  103. def wait(self):
  104. """Wait until switch() or throw() is called.
  105. """
  106. assert self.greenlet is None, 'This Waiter is already used by %r' % (self.greenlet, )
  107. self.greenlet = getcurrent()
  108. try:
  109. return get_hub().switch()
  110. finally:
  111. self.greenlet = None
  112. class LightQueue(object):
  113. """
  114. This is a variant of Queue that behaves mostly like the standard
  115. :class:`Queue`. It differs by not supporting the
  116. :meth:`task_done <Queue.task_done>` or :meth:`join <Queue.join>` methods,
  117. and is a little faster for not having that overhead.
  118. """
  119. def __init__(self, maxsize=None):
  120. if maxsize is None or maxsize < 0: #None is not comparable in 3.x
  121. self.maxsize = None
  122. else:
  123. self.maxsize = maxsize
  124. self.getters = set()
  125. self.putters = set()
  126. self._event_unlock = None
  127. self._init(maxsize)
  128. # QQQ make maxsize into a property with setter that schedules unlock if necessary
  129. def _init(self, maxsize):
  130. self.queue = collections.deque()
  131. def _get(self):
  132. return self.queue.popleft()
  133. def _put(self, item):
  134. self.queue.append(item)
  135. def __repr__(self):
  136. return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._format())
  137. def __str__(self):
  138. return '<%s %s>' % (type(self).__name__, self._format())
  139. def _format(self):
  140. result = 'maxsize=%r' % (self.maxsize, )
  141. if getattr(self, 'queue', None):
  142. result += ' queue=%r' % self.queue
  143. if self.getters:
  144. result += ' getters[%s]' % len(self.getters)
  145. if self.putters:
  146. result += ' putters[%s]' % len(self.putters)
  147. if self._event_unlock is not None:
  148. result += ' unlocking'
  149. return result
  150. def qsize(self):
  151. """Return the size of the queue."""
  152. return len(self.queue)
  153. def resize(self, size):
  154. """Resizes the queue's maximum size.
  155. If the size is increased, and there are putters waiting, they may be woken up."""
  156. if self.maxsize is not None and (size is None or size > self.maxsize): # None is not comparable in 3.x
  157. # Maybe wake some stuff up
  158. self._schedule_unlock()
  159. self.maxsize = size
  160. def putting(self):
  161. """Returns the number of greenthreads that are blocked waiting to put
  162. items into the queue."""
  163. return len(self.putters)
  164. def getting(self):
  165. """Returns the number of greenthreads that are blocked waiting on an
  166. empty queue."""
  167. return len(self.getters)
  168. def empty(self):
  169. """Return ``True`` if the queue is empty, ``False`` otherwise."""
  170. return not self.qsize()
  171. def full(self):
  172. """Return ``True`` if the queue is full, ``False`` otherwise.
  173. ``Queue(None)`` is never full.
  174. """
  175. return self.maxsize is not None and self.qsize() >= self.maxsize # None is not comparable in 3.x
  176. def put(self, item, block=True, timeout=None):
  177. """Put an item into the queue.
  178. If optional arg *block* is true and *timeout* is ``None`` (the default),
  179. block if necessary until a free slot is available. If *timeout* is
  180. a positive number, it blocks at most *timeout* seconds and raises
  181. the :class:`Full` exception if no free slot was available within that time.
  182. Otherwise (*block* is false), put an item on the queue if a free slot
  183. is immediately available, else raise the :class:`Full` exception (*timeout*
  184. is ignored in that case).
  185. """
  186. if self.maxsize is None or self.qsize() < self.maxsize:
  187. # there's a free slot, put an item right away
  188. self._put(item)
  189. if self.getters:
  190. self._schedule_unlock()
  191. elif not block and get_hub().greenlet is getcurrent():
  192. # we're in the mainloop, so we cannot wait; we can switch() to other greenlets though
  193. # find a getter and deliver an item to it
  194. while self.getters:
  195. getter = self.getters.pop()
  196. if getter:
  197. self._put(item)
  198. item = self._get()
  199. getter.switch(item)
  200. return
  201. raise Full
  202. elif block:
  203. waiter = ItemWaiter(item)
  204. self.putters.add(waiter)
  205. timeout = Timeout(timeout, Full)
  206. try:
  207. if self.getters:
  208. self._schedule_unlock()
  209. result = waiter.wait()
  210. assert result is waiter, "Invalid switch into Queue.put: %r" % (result, )
  211. if waiter.item is not _NONE:
  212. self._put(item)
  213. finally:
  214. timeout.cancel()
  215. self.putters.discard(waiter)
  216. else:
  217. raise Full
  218. def put_nowait(self, item):
  219. """Put an item into the queue without blocking.
  220. Only enqueue the item if a free slot is immediately available.
  221. Otherwise raise the :class:`Full` exception.
  222. """
  223. self.put(item, False)
  224. def get(self, block=True, timeout=None):
  225. """Remove and return an item from the queue.
  226. If optional args *block* is true and *timeout* is ``None`` (the default),
  227. block if necessary until an item is available. If *timeout* is a positive number,
  228. it blocks at most *timeout* seconds and raises the :class:`Empty` exception
  229. if no item was available within that time. Otherwise (*block* is false), return
  230. an item if one is immediately available, else raise the :class:`Empty` exception
  231. (*timeout* is ignored in that case).
  232. """
  233. if self.qsize():
  234. if self.putters:
  235. self._schedule_unlock()
  236. return self._get()
  237. elif not block and get_hub().greenlet is getcurrent():
  238. # special case to make get_nowait() runnable in the mainloop greenlet
  239. # there are no items in the queue; try to fix the situation by unlocking putters
  240. while self.putters:
  241. putter = self.putters.pop()
  242. if putter:
  243. putter.switch(putter)
  244. if self.qsize():
  245. return self._get()
  246. raise Empty
  247. elif block:
  248. waiter = Waiter()
  249. timeout = Timeout(timeout, Empty)
  250. try:
  251. self.getters.add(waiter)
  252. if self.putters:
  253. self._schedule_unlock()
  254. return waiter.wait()
  255. finally:
  256. self.getters.discard(waiter)
  257. timeout.cancel()
  258. else:
  259. raise Empty
  260. def get_nowait(self):
  261. """Remove and return an item from the queue without blocking.
  262. Only get an item if one is immediately available. Otherwise
  263. raise the :class:`Empty` exception.
  264. """
  265. return self.get(False)
  266. def _unlock(self):
  267. try:
  268. while True:
  269. if self.qsize() and self.getters:
  270. getter = self.getters.pop()
  271. if getter:
  272. try:
  273. item = self._get()
  274. except:
  275. getter.throw(*sys.exc_info())
  276. else:
  277. getter.switch(item)
  278. elif self.putters and self.getters:
  279. putter = self.putters.pop()
  280. if putter:
  281. getter = self.getters.pop()
  282. if getter:
  283. item = putter.item
  284. putter.item = _NONE # this makes greenlet calling put() not to call _put() again
  285. self._put(item)
  286. item = self._get()
  287. getter.switch(item)
  288. putter.switch(putter)
  289. else:
  290. self.putters.add(putter)
  291. elif self.putters and (self.getters or self.maxsize is None or self.qsize() < self.maxsize):
  292. putter = self.putters.pop()
  293. putter.switch(putter)
  294. else:
  295. break
  296. finally:
  297. self._event_unlock = None # QQQ maybe it's possible to obtain this info from libevent?
  298. # i.e. whether this event is pending _OR_ currently executing
  299. # testcase: 2 greenlets: while True: q.put(q.get()) - nothing else has a change to execute
  300. # to avoid this, schedule unlock with timer(0, ...) once in a while
  301. def _schedule_unlock(self):
  302. if self._event_unlock is None:
  303. self._event_unlock = get_hub().schedule_call_global(0, self._unlock)
  304. class ItemWaiter(Waiter):
  305. __slots__ = ['item']
  306. def __init__(self, item):
  307. Waiter.__init__(self)
  308. self.item = item
  309. class Queue(LightQueue):
  310. '''Create a queue object with a given maximum size.
  311. If *maxsize* is less than zero or ``None``, the queue size is infinite.
  312. ``Queue(0)`` is a channel, that is, its :meth:`put` method always blocks
  313. until the item is delivered. (This is unlike the standard :class:`Queue`,
  314. where 0 means infinite size).
  315. In all other respects, this Queue class resembled the standard library,
  316. :class:`Queue`.
  317. '''
  318. def __init__(self, maxsize=None):
  319. LightQueue.__init__(self, maxsize)
  320. self.unfinished_tasks = 0
  321. self._cond = Event()
  322. def _format(self):
  323. result = LightQueue._format(self)
  324. if self.unfinished_tasks:
  325. result += ' tasks=%s _cond=%s' % (self.unfinished_tasks, self._cond)
  326. return result
  327. def _put(self, item):
  328. LightQueue._put(self, item)
  329. self._put_bookkeeping()
  330. def _put_bookkeeping(self):
  331. self.unfinished_tasks += 1
  332. if self._cond.ready():
  333. self._cond.reset()
  334. def task_done(self):
  335. '''Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
  336. For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue
  337. that the processing on the task is complete.
  338. If a :meth:`join` is currently blocking, it will resume when all items have been processed
  339. (meaning that a :meth:`task_done` call was received for every item that had been
  340. :meth:`put <Queue.put>` into the queue).
  341. Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
  342. '''
  343. if self.unfinished_tasks <= 0:
  344. raise ValueError('task_done() called too many times')
  345. self.unfinished_tasks -= 1
  346. if self.unfinished_tasks == 0:
  347. self._cond.send(None)
  348. def join(self):
  349. '''Block until all items in the queue have been gotten and processed.
  350. The count of unfinished tasks goes up whenever an item is added to the queue.
  351. The count goes down whenever a consumer thread calls :meth:`task_done` to indicate
  352. that the item was retrieved and all work on it is complete. When the count of
  353. unfinished tasks drops to zero, :meth:`join` unblocks.
  354. '''
  355. self._cond.wait()
  356. class PriorityQueue(Queue):
  357. '''A subclass of :class:`Queue` that retrieves entries in priority order (lowest first).
  358. Entries are typically tuples of the form: ``(priority number, data)``.
  359. '''
  360. def _init(self, maxsize):
  361. self.queue = []
  362. def _put(self, item, heappush=heapq.heappush):
  363. heappush(self.queue, item)
  364. self._put_bookkeeping()
  365. def _get(self, heappop=heapq.heappop):
  366. return heappop(self.queue)
  367. class LifoQueue(Queue):
  368. '''A subclass of :class:`Queue` that retrieves most recently added entries first.'''
  369. def _init(self, maxsize):
  370. self.queue = []
  371. def _put(self, item):
  372. self.queue.append(item)
  373. self._put_bookkeeping()
  374. def _get(self):
  375. return self.queue.pop()