Queue.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. def __init__(self, maxsize=0):
  13. """Initialize a queue object with a given maximum size.
  14. If maxsize is <= 0, the queue size is infinite.
  15. """
  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 two 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. def qsize(self):
  33. """Return the approximate size of the queue (not reliable!)."""
  34. self.mutex.acquire()
  35. n = self._qsize()
  36. self.mutex.release()
  37. return n
  38. def empty(self):
  39. """Return True if the queue is empty, False otherwise (not reliable!)."""
  40. self.mutex.acquire()
  41. n = self._empty()
  42. self.mutex.release()
  43. return n
  44. def full(self):
  45. """Return True if the queue is full, False otherwise (not reliable!)."""
  46. self.mutex.acquire()
  47. n = self._full()
  48. self.mutex.release()
  49. return n
  50. def put(self, item, block=True, timeout=None):
  51. """Put an item into the queue.
  52. If optional args 'block' is true and 'timeout' is None (the default),
  53. block if necessary until a free slot is available. If 'timeout' is
  54. a positive number, it blocks at most 'timeout' seconds and raises
  55. the Full exception if no free slot was available within that time.
  56. Otherwise ('block' is false), put an item on the queue if a free slot
  57. is immediately available, else raise the Full exception ('timeout'
  58. is ignored in that case).
  59. """
  60. self.not_full.acquire()
  61. try:
  62. if not block:
  63. if self._full():
  64. raise Full
  65. elif timeout is None:
  66. while self._full():
  67. self.not_full.wait()
  68. else:
  69. if timeout < 0:
  70. raise ValueError("'timeout' must be a positive number")
  71. endtime = _time() + timeout
  72. while self._full():
  73. remaining = endtime - _time()
  74. if remaining <= 0.0:
  75. raise Full
  76. self.not_full.wait(remaining)
  77. self._put(item)
  78. self.not_empty.notify()
  79. finally:
  80. self.not_full.release()
  81. def put_nowait(self, item):
  82. """Put an item into the queue without blocking.
  83. Only enqueue the item if a free slot is immediately available.
  84. Otherwise raise the Full exception.
  85. """
  86. return self.put(item, False)
  87. def get(self, block=True, timeout=None):
  88. """Remove and return an item from the queue.
  89. If optional args 'block' is true and 'timeout' is None (the default),
  90. block if necessary until an item is available. If 'timeout' is
  91. a positive number, it blocks at most 'timeout' seconds and raises
  92. the Empty exception if no item was available within that time.
  93. Otherwise ('block' is false), return an item if one is immediately
  94. available, else raise the Empty exception ('timeout' is ignored
  95. in that case).
  96. """
  97. self.not_empty.acquire()
  98. try:
  99. if not block:
  100. if self._empty():
  101. raise Empty
  102. elif timeout is None:
  103. while self._empty():
  104. self.not_empty.wait()
  105. else:
  106. if timeout < 0:
  107. raise ValueError("'timeout' must be a positive number")
  108. endtime = _time() + timeout
  109. while self._empty():
  110. remaining = endtime - _time()
  111. if remaining <= 0.0:
  112. raise Empty
  113. self.not_empty.wait(remaining)
  114. item = self._get()
  115. self.not_full.notify()
  116. return item
  117. finally:
  118. self.not_empty.release()
  119. def get_nowait(self):
  120. """Remove and return an item from the queue without blocking.
  121. Only get an item if one is immediately available. Otherwise
  122. raise the Empty exception.
  123. """
  124. return self.get(False)
  125. # Override these methods to implement other queue organizations
  126. # (e.g. stack or priority queue).
  127. # These will only be called with appropriate locks held
  128. # Initialize the queue representation
  129. def _init(self, maxsize):
  130. self.maxsize = maxsize
  131. self.queue = deque()
  132. def _qsize(self):
  133. return len(self.queue)
  134. # Check whether the queue is empty
  135. def _empty(self):
  136. return not self.queue
  137. # Check whether the queue is full
  138. def _full(self):
  139. return self.maxsize > 0 and len(self.queue) == self.maxsize
  140. # Put a new item in the queue
  141. def _put(self, item):
  142. self.queue.append(item)
  143. # Get an item from the queue
  144. def _get(self):
  145. return self.queue.popleft()