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