Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 1 | """A multi-producer, multi-consumer queue.""" |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 2 | |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 3 | from time import time as _time |
Raymond Hettinger | 756b3f3 | 2004-01-29 06:37:52 +0000 | [diff] [blame] | 4 | from collections import deque |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 5 | import heapq |
Martin v. Löwis | 77ac429 | 2002-10-15 15:11:13 +0000 | [diff] [blame] | 6 | |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 7 | __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] |
Brett Cannon | b42bb5a | 2003-07-01 05:34:27 +0000 | [diff] [blame] | 8 | |
Tim Peters | b8c9417 | 2001-01-15 22:53:46 +0000 | [diff] [blame] | 9 | class Empty(Exception): |
| 10 | "Exception raised by Queue.get(block=0)/get_nowait()." |
| 11 | pass |
| 12 | |
| 13 | class Full(Exception): |
| 14 | "Exception raised by Queue.put(block=0)/put_nowait()." |
| 15 | pass |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 16 | |
| 17 | class Queue: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 18 | """Create a queue object with a given maximum size. |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 19 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 20 | If maxsize is <= 0, the queue size is infinite. |
| 21 | """ |
| 22 | def __init__(self, maxsize=0): |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 23 | try: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 24 | import threading |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 25 | except ImportError: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 26 | import dummy_threading as threading |
Raymond Hettinger | da3caed | 2008-01-14 21:39:24 +0000 | [diff] [blame] | 27 | self.maxsize = maxsize |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 28 | self._init(maxsize) |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 29 | # mutex must be held whenever the queue is mutating. All methods |
| 30 | # that acquire mutex must release it before returning. mutex |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 31 | # is shared between the three conditions, so acquiring and |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 32 | # releasing the conditions also acquires and releases mutex. |
| 33 | self.mutex = threading.Lock() |
| 34 | # Notify not_empty whenever an item is added to the queue; a |
| 35 | # thread waiting to get is notified then. |
| 36 | self.not_empty = threading.Condition(self.mutex) |
| 37 | # Notify not_full whenever an item is removed from the queue; |
| 38 | # a thread waiting to put is notified then. |
| 39 | self.not_full = threading.Condition(self.mutex) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 40 | # Notify all_tasks_done whenever the number of unfinished tasks |
| 41 | # drops to zero; thread waiting to join() is notified to resume |
| 42 | self.all_tasks_done = threading.Condition(self.mutex) |
| 43 | self.unfinished_tasks = 0 |
| 44 | |
| 45 | def task_done(self): |
| 46 | """Indicate that a formerly enqueued task is complete. |
| 47 | |
| 48 | Used by Queue consumer threads. For each get() used to fetch a task, |
| 49 | a subsequent call to task_done() tells the queue that the processing |
| 50 | on the task is complete. |
| 51 | |
| 52 | If a join() is currently blocking, it will resume when all items |
| 53 | have been processed (meaning that a task_done() call was received |
| 54 | for every item that had been put() into the queue). |
| 55 | |
| 56 | Raises a ValueError if called more times than there were items |
| 57 | placed in the queue. |
| 58 | """ |
| 59 | self.all_tasks_done.acquire() |
| 60 | try: |
| 61 | unfinished = self.unfinished_tasks - 1 |
| 62 | if unfinished <= 0: |
| 63 | if unfinished < 0: |
| 64 | raise ValueError('task_done() called too many times') |
| 65 | self.all_tasks_done.notifyAll() |
| 66 | self.unfinished_tasks = unfinished |
| 67 | finally: |
| 68 | self.all_tasks_done.release() |
| 69 | |
| 70 | def join(self): |
| 71 | """Blocks until all items in the Queue have been gotten and processed. |
| 72 | |
| 73 | The count of unfinished tasks goes up whenever an item is added to the |
| 74 | queue. The count goes down whenever a consumer thread calls task_done() |
| 75 | to indicate the item was retrieved and all work on it is complete. |
| 76 | |
| 77 | When the count of unfinished tasks drops to zero, join() unblocks. |
| 78 | """ |
| 79 | self.all_tasks_done.acquire() |
| 80 | try: |
| 81 | while self.unfinished_tasks: |
| 82 | self.all_tasks_done.wait() |
| 83 | finally: |
| 84 | self.all_tasks_done.release() |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 85 | |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 86 | def qsize(self): |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 87 | """Return the approximate size of the queue (not reliable!).""" |
Guido van Rossum | 7e6d18c | 1998-04-29 14:29:32 +0000 | [diff] [blame] | 88 | self.mutex.acquire() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 89 | n = self._qsize() |
Guido van Rossum | 7e6d18c | 1998-04-29 14:29:32 +0000 | [diff] [blame] | 90 | self.mutex.release() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 91 | return n |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 92 | |
Martin v. Löwis | 77ac429 | 2002-10-15 15:11:13 +0000 | [diff] [blame] | 93 | def put(self, item, block=True, timeout=None): |
Guido van Rossum | c09e6b1 | 1998-04-09 14:25:32 +0000 | [diff] [blame] | 94 | """Put an item into the queue. |
| 95 | |
Martin v. Löwis | 77ac429 | 2002-10-15 15:11:13 +0000 | [diff] [blame] | 96 | If optional args 'block' is true and 'timeout' is None (the default), |
| 97 | block if necessary until a free slot is available. If 'timeout' is |
| 98 | a positive number, it blocks at most 'timeout' seconds and raises |
| 99 | the Full exception if no free slot was available within that time. |
| 100 | Otherwise ('block' is false), put an item on the queue if a free slot |
| 101 | is immediately available, else raise the Full exception ('timeout' |
| 102 | is ignored in that case). |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 103 | """ |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 104 | self.not_full.acquire() |
Mark Hammond | 3b959db | 2002-04-19 00:11:32 +0000 | [diff] [blame] | 105 | try: |
Raymond Hettinger | ae138cb | 2008-01-15 20:42:00 +0000 | [diff] [blame] | 106 | if self.maxsize > 0: |
| 107 | if not block: |
| 108 | if self._qsize() == self.maxsize: |
| 109 | raise Full |
| 110 | elif timeout is None: |
Raymond Hettinger | da3caed | 2008-01-14 21:39:24 +0000 | [diff] [blame] | 111 | while self._qsize() == self.maxsize: |
| 112 | self.not_full.wait() |
Raymond Hettinger | ae138cb | 2008-01-15 20:42:00 +0000 | [diff] [blame] | 113 | elif timeout < 0: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 114 | raise ValueError("'timeout' must be a positive number") |
Raymond Hettinger | ae138cb | 2008-01-15 20:42:00 +0000 | [diff] [blame] | 115 | else: |
| 116 | endtime = _time() + timeout |
Raymond Hettinger | da3caed | 2008-01-14 21:39:24 +0000 | [diff] [blame] | 117 | while self._qsize() == self.maxsize: |
| 118 | remaining = endtime - _time() |
| 119 | if remaining <= 0.0: |
| 120 | raise Full |
| 121 | self.not_full.wait(remaining) |
Mark Hammond | 3b959db | 2002-04-19 00:11:32 +0000 | [diff] [blame] | 122 | self._put(item) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 123 | self.unfinished_tasks += 1 |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 124 | self.not_empty.notify() |
Mark Hammond | 3b959db | 2002-04-19 00:11:32 +0000 | [diff] [blame] | 125 | finally: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 126 | self.not_full.release() |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 127 | |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 128 | def put_nowait(self, item): |
| 129 | """Put an item into the queue without blocking. |
Guido van Rossum | c09e6b1 | 1998-04-09 14:25:32 +0000 | [diff] [blame] | 130 | |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 131 | Only enqueue the item if a free slot is immediately available. |
| 132 | Otherwise raise the Full exception. |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 133 | """ |
Tim Peters | 71ed220 | 2004-07-12 01:20:32 +0000 | [diff] [blame] | 134 | return self.put(item, False) |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 135 | |
Martin v. Löwis | 77ac429 | 2002-10-15 15:11:13 +0000 | [diff] [blame] | 136 | def get(self, block=True, timeout=None): |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 137 | """Remove and return an item from the queue. |
Guido van Rossum | c09e6b1 | 1998-04-09 14:25:32 +0000 | [diff] [blame] | 138 | |
Martin v. Löwis | 77ac429 | 2002-10-15 15:11:13 +0000 | [diff] [blame] | 139 | If optional args 'block' is true and 'timeout' is None (the default), |
| 140 | block if necessary until an item is available. If 'timeout' is |
| 141 | a positive number, it blocks at most 'timeout' seconds and raises |
| 142 | the Empty exception if no item was available within that time. |
| 143 | Otherwise ('block' is false), return an item if one is immediately |
| 144 | available, else raise the Empty exception ('timeout' is ignored |
| 145 | in that case). |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 146 | """ |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 147 | self.not_empty.acquire() |
Mark Hammond | 3b959db | 2002-04-19 00:11:32 +0000 | [diff] [blame] | 148 | try: |
Tim Peters | 71ed220 | 2004-07-12 01:20:32 +0000 | [diff] [blame] | 149 | if not block: |
Raymond Hettinger | da3caed | 2008-01-14 21:39:24 +0000 | [diff] [blame] | 150 | if not self._qsize(): |
Tim Peters | 71ed220 | 2004-07-12 01:20:32 +0000 | [diff] [blame] | 151 | raise Empty |
| 152 | elif timeout is None: |
Raymond Hettinger | da3caed | 2008-01-14 21:39:24 +0000 | [diff] [blame] | 153 | while not self._qsize(): |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 154 | self.not_empty.wait() |
Raymond Hettinger | ae138cb | 2008-01-15 20:42:00 +0000 | [diff] [blame] | 155 | elif timeout < 0: |
| 156 | raise ValueError("'timeout' must be a positive number") |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 157 | else: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 158 | endtime = _time() + timeout |
Raymond Hettinger | da3caed | 2008-01-14 21:39:24 +0000 | [diff] [blame] | 159 | while not self._qsize(): |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 160 | remaining = endtime - _time() |
Tim Peters | 71ed220 | 2004-07-12 01:20:32 +0000 | [diff] [blame] | 161 | if remaining <= 0.0: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 162 | raise Empty |
| 163 | self.not_empty.wait(remaining) |
Mark Hammond | 3b959db | 2002-04-19 00:11:32 +0000 | [diff] [blame] | 164 | item = self._get() |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 165 | self.not_full.notify() |
| 166 | return item |
Mark Hammond | 3b959db | 2002-04-19 00:11:32 +0000 | [diff] [blame] | 167 | finally: |
Tim Peters | 5af0e41 | 2004-07-12 00:45:14 +0000 | [diff] [blame] | 168 | self.not_empty.release() |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 169 | |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 170 | def get_nowait(self): |
| 171 | """Remove and return an item from the queue without blocking. |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 172 | |
Martin v. Löwis | 77ac429 | 2002-10-15 15:11:13 +0000 | [diff] [blame] | 173 | Only get an item if one is immediately available. Otherwise |
Guido van Rossum | 9e1721f | 1999-02-08 18:34:01 +0000 | [diff] [blame] | 174 | raise the Empty exception. |
| 175 | """ |
Tim Peters | 71ed220 | 2004-07-12 01:20:32 +0000 | [diff] [blame] | 176 | return self.get(False) |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 177 | |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 178 | # Override these methods to implement other queue organizations |
| 179 | # (e.g. stack or priority queue). |
| 180 | # These will only be called with appropriate locks held |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 181 | |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 182 | # Initialize the queue representation |
| 183 | def _init(self, maxsize): |
Raymond Hettinger | 756b3f3 | 2004-01-29 06:37:52 +0000 | [diff] [blame] | 184 | self.queue = deque() |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 185 | |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 186 | def _qsize(self, len=len): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 187 | return len(self.queue) |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 188 | |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 189 | # Put a new item in the queue |
| 190 | def _put(self, item): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 191 | self.queue.append(item) |
Guido van Rossum | 9022fce | 1992-08-25 12:30:44 +0000 | [diff] [blame] | 192 | |
Barry Warsaw | 3d96d52 | 1997-11-20 19:56:38 +0000 | [diff] [blame] | 193 | # Get an item from the queue |
| 194 | def _get(self): |
Raymond Hettinger | 756b3f3 | 2004-01-29 06:37:52 +0000 | [diff] [blame] | 195 | return self.queue.popleft() |
Raymond Hettinger | 3564146 | 2008-01-17 00:13:27 +0000 | [diff] [blame] | 196 | |
| 197 | |
| 198 | class PriorityQueue(Queue): |
| 199 | '''Variant of Queue that retrieves open entries in priority order (lowest first). |
| 200 | |
| 201 | Entries are typically tuples of the form: (priority number, data). |
| 202 | ''' |
| 203 | |
| 204 | def _init(self, maxsize): |
| 205 | self.queue = [] |
| 206 | |
| 207 | def _qsize(self, len=len): |
| 208 | return len(self.queue) |
| 209 | |
| 210 | def _put(self, item, heappush=heapq.heappush): |
| 211 | heappush(self.queue, item) |
| 212 | |
| 213 | def _get(self, heappop=heapq.heappop): |
| 214 | return heappop(self.queue) |
| 215 | |
| 216 | |
| 217 | class LifoQueue(Queue): |
| 218 | '''Variant of Queue that retrieves most recently added entries first.''' |
| 219 | |
| 220 | def _init(self, maxsize): |
| 221 | self.queue = [] |
| 222 | |
| 223 | def _qsize(self, len=len): |
| 224 | return len(self.queue) |
| 225 | |
| 226 | def _put(self, item): |
| 227 | self.queue.append(item) |
| 228 | |
| 229 | def _get(self): |
| 230 | return self.queue.pop() |