Py25Queue.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. """A multi-producer, multi-consumer queue."""
  2. from time import time as _time
  3. from collections import deque
  4. __all__ = ['Empty', 'Full', 'Queue']
  5. class Empty(Exception):
  6. "Exception raised by Queue.get(block=0)/get_nowait()."
  7. pass
  8. class Full(Exception):
  9. "Exception raised by Queue.put(block=0)/put_nowait()."
  10. pass
  11. class Queue:
  12. """Create a queue object with a given maximum size.
  13. If maxsize is <= 0, the queue size is infinite.
  14. """
  15. def __init__(self, maxsize=0):
  16. try:
  17. import threading
  18. except ImportError:
  19. import dummy_threading as threading
  20. self._init(maxsize)
  21. # mutex must be held whenever the queue is mutating. All methods
  22. # that acquire mutex must release it before returning. mutex
  23. # is shared between the three conditions, so acquiring and
  24. # releasing the conditions also acquires and releases mutex.
  25. self.mutex = threading.Lock()
  26. # Notify not_empty whenever an item is added to the queue; a
  27. # thread waiting to get is notified then.
  28. self.not_empty = threading.Condition(self.mutex)
  29. # Notify not_full whenever an item is removed from the queue;
  30. # a thread waiting to put is notified then.
  31. self.not_full = threading.Condition(self.mutex)
  32. # Notify all_tasks_done whenever the number of unfinished tasks
  33. # drops to zero; thread waiting to join() is notified to resume
  34. self.all_tasks_done = threading.Condition(self.mutex)
  35. self.unfinished_tasks = 0
  36. def task_done(self):
  37. """Indicate that a formerly enqueued task is complete.
  38. Used by Queue consumer threads. For each get() used to fetch a task,
  39. a subsequent call to task_done() tells the queue that the processing
  40. on the task is complete.
  41. If a join() is currently blocking, it will resume when all items
  42. have been processed (meaning that a task_done() call was received
  43. for every item that had been put() into the queue).
  44. Raises a ValueError if called more times than there were items
  45. placed in the queue.
  46. """
  47. self.all_tasks_done.acquire()
  48. try:
  49. unfinished = self.unfinished_tasks - 1
  50. if unfinished <= 0:
  51. if unfinished < 0:
  52. raise ValueError('task_done() called too many times')
  53. self.all_tasks_done.notifyAll()
  54. self.unfinished_tasks = unfinished
  55. finally:
  56. self.all_tasks_done.release()
  57. def join(self):
  58. """Blocks until all items in the Queue have been gotten and processed.
  59. The count of unfinished tasks goes up whenever an item is added to the
  60. queue. The count goes down whenever a consumer thread calls task_done()
  61. to indicate the item was retrieved and all work on it is complete.
  62. When the count of unfinished tasks drops to zero, join() unblocks.
  63. """
  64. self.all_tasks_done.acquire()
  65. try:
  66. while self.unfinished_tasks:
  67. self.all_tasks_done.wait()
  68. finally:
  69. self.all_tasks_done.release()
  70. def qsize(self):
  71. """Return the approximate size of the queue (not reliable!)."""
  72. self.mutex.acquire()
  73. n = self._qsize()
  74. self.mutex.release()
  75. return n
  76. def empty(self):
  77. """Return True if the queue is empty, False otherwise (not reliable!)."""
  78. self.mutex.acquire()
  79. n = self._empty()
  80. self.mutex.release()
  81. return n
  82. def full(self):
  83. """Return True if the queue is full, False otherwise (not reliable!)."""
  84. self.mutex.acquire()
  85. n = self._full()
  86. self.mutex.release()
  87. return n
  88. def put(self, item, block=True, timeout=None):
  89. """Put an item into the queue.
  90. If optional args 'block' is true and 'timeout' is None (the default),
  91. block if necessary until a free slot is available. If 'timeout' is
  92. a positive number, it blocks at most 'timeout' seconds and raises
  93. the Full exception if no free slot was available within that time.
  94. Otherwise ('block' is false), put an item on the queue if a free slot
  95. is immediately available, else raise the Full exception ('timeout'
  96. is ignored in that case).
  97. """
  98. self.not_full.acquire()
  99. try:
  100. if not block:
  101. if self._full():
  102. raise Full
  103. elif timeout is None:
  104. while self._full():
  105. self.not_full.wait()
  106. else:
  107. if timeout < 0:
  108. raise ValueError("'timeout' must be a positive number")
  109. endtime = _time() + timeout
  110. while self._full():
  111. remaining = endtime - _time()
  112. if remaining <= 0.0:
  113. raise Full
  114. self.not_full.wait(remaining)
  115. self._put(item)
  116. self.unfinished_tasks += 1
  117. self.not_empty.notify()
  118. finally:
  119. self.not_full.release()
  120. def put_nowait(self, item):
  121. """Put an item into the queue without blocking.
  122. Only enqueue the item if a free slot is immediately available.
  123. Otherwise raise the Full exception.
  124. """
  125. return self.put(item, False)
  126. def get(self, block=True, timeout=None):
  127. """Remove and return an item from the queue.
  128. If optional args 'block' is true and 'timeout' is None (the default),
  129. block if necessary until an item is available. If 'timeout' is
  130. a positive number, it blocks at most 'timeout' seconds and raises
  131. the Empty exception if no item was available within that time.
  132. Otherwise ('block' is false), return an item if one is immediately
  133. available, else raise the Empty exception ('timeout' is ignored
  134. in that case).
  135. """
  136. self.not_empty.acquire()
  137. try:
  138. if not block:
  139. if self._empty():
  140. raise Empty
  141. elif timeout is None:
  142. while self._empty():
  143. self.not_empty.wait()
  144. else:
  145. if timeout < 0:
  146. raise ValueError("'timeout' must be a positive number")
  147. endtime = _time() + timeout
  148. while self._empty():
  149. remaining = endtime - _time()
  150. if remaining <= 0.0:
  151. raise Empty
  152. self.not_empty.wait(remaining)
  153. item = self._get()
  154. self.not_full.notify()
  155. return item
  156. finally:
  157. self.not_empty.release()
  158. def get_nowait(self):
  159. """Remove and return an item from the queue without blocking.
  160. Only get an item if one is immediately available. Otherwise
  161. raise the Empty exception.
  162. """
  163. return self.get(False)
  164. # Override these methods to implement other queue organizations
  165. # (e.g. stack or priority queue).
  166. # These will only be called with appropriate locks held
  167. # Initialize the queue representation
  168. def _init(self, maxsize):
  169. self.maxsize = maxsize
  170. self.queue = deque()
  171. def _qsize(self):
  172. return len(self.queue)
  173. # Check whether the queue is empty
  174. def _empty(self):
  175. return not self.queue
  176. # Check whether the queue is full
  177. def _full(self):
  178. return self.maxsize > 0 and len(self.queue) == self.maxsize
  179. # Put a new item in the queue
  180. def _put(self, item):
  181. self.queue.append(item)
  182. # Get an item from the queue
  183. def _get(self):
  184. return self.queue.popleft()