blob: 285cd17da68893800eb402efdb21e5aef39dd862 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""A multi-producer, multi-consumer queue."""
Guido van Rossum9022fce1992-08-25 12:30:44 +00002
Tim Peters5af0e412004-07-12 00:45:14 +00003from time import time as _time
Raymond Hettinger756b3f32004-01-29 06:37:52 +00004from collections import deque
Martin v. Löwis77ac4292002-10-15 15:11:13 +00005
Brett Cannonb42bb5a2003-07-01 05:34:27 +00006__all__ = ['Empty', 'Full', 'Queue']
7
Tim Petersb8c94172001-01-15 22:53:46 +00008class Empty(Exception):
9 "Exception raised by Queue.get(block=0)/get_nowait()."
10 pass
11
12class Full(Exception):
13 "Exception raised by Queue.put(block=0)/put_nowait()."
14 pass
Guido van Rossum9022fce1992-08-25 12:30:44 +000015
16class Queue:
Guido van Rossuma41c6911999-09-09 14:54:28 +000017 def __init__(self, maxsize=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000018 """Initialize a queue object with a given maximum size.
Guido van Rossum9022fce1992-08-25 12:30:44 +000019
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000020 If maxsize is <= 0, the queue size is infinite.
21 """
Guido van Rossuma0934242002-12-30 22:36:09 +000022 try:
Tim Peters5af0e412004-07-12 00:45:14 +000023 import threading
Guido van Rossuma0934242002-12-30 22:36:09 +000024 except ImportError:
Tim Peters5af0e412004-07-12 00:45:14 +000025 import dummy_threading as threading
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000026 self._init(maxsize)
Tim Peters5af0e412004-07-12 00:45:14 +000027 # mutex must be held whenever the queue is mutating. All methods
28 # that acquire mutex must release it before returning. mutex
29 # is shared between the two conditions, so acquiring and
30 # releasing the conditions also acquires and releases mutex.
31 self.mutex = threading.Lock()
32 # Notify not_empty whenever an item is added to the queue; a
33 # thread waiting to get is notified then.
34 self.not_empty = threading.Condition(self.mutex)
35 # Notify not_full whenever an item is removed from the queue;
36 # a thread waiting to put is notified then.
37 self.not_full = threading.Condition(self.mutex)
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +000038 # Notify all_tasks_done whenever the number of unfinished tasks
39 # drops to zero; thread waiting to join() is notified to resume
40 self.all_tasks_done = threading.Condition(self.mutex)
41 self.unfinished_tasks = 0
42
43 def task_done(self):
44 """Indicate that a formerly enqueued task is complete.
45
46 Used by Queue consumer threads. For each get() used to fetch a task,
47 a subsequent call to task_done() tells the queue that the processing
48 on the task is complete.
49
50 If a join() is currently blocking, it will resume when all items
51 have been processed (meaning that a task_done() call was received
52 for every item that had been put() into the queue).
53
54 Raises a ValueError if called more times than there were items
55 placed in the queue.
56 """
57 self.all_tasks_done.acquire()
58 try:
59 self.unfinished_tasks = unfinished = self.unfinished_tasks - 1
60 if unfinished <= 0:
61 if unfinished < 0:
62 raise ValueError('task_done() called too many times')
63 self.all_tasks_done.notifyAll()
64 finally:
65 self.all_tasks_done.release()
66
67 def join(self):
68 """Blocks until all items in the Queue have been gotten and processed.
69
70 The count of unfinished tasks goes up whenever an item is added to the
71 queue. The count goes down whenever a consumer thread calls task_done()
72 to indicate the item was retrieved and all work on it is complete.
73
74 When the count of unfinished tasks drops to zero, join() unblocks.
75 """
76 self.all_tasks_done.acquire()
77 try:
78 while self.unfinished_tasks:
79 self.all_tasks_done.wait()
80 finally:
81 self.all_tasks_done.release()
Guido van Rossum9022fce1992-08-25 12:30:44 +000082
Barry Warsaw3d96d521997-11-20 19:56:38 +000083 def qsize(self):
Guido van Rossum9e1721f1999-02-08 18:34:01 +000084 """Return the approximate size of the queue (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000085 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000086 n = self._qsize()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000087 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000089
90 def empty(self):
Martin v. Löwis77ac4292002-10-15 15:11:13 +000091 """Return True if the queue is empty, False otherwise (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000092 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000093 n = self._empty()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000094 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000095 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000096
97 def full(self):
Martin v. Löwis77ac4292002-10-15 15:11:13 +000098 """Return True if the queue is full, False otherwise (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000099 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 n = self._full()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +0000101 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000102 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +0000103
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000104 def put(self, item, block=True, timeout=None):
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000105 """Put an item into the queue.
106
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000107 If optional args 'block' is true and 'timeout' is None (the default),
108 block if necessary until a free slot is available. If 'timeout' is
109 a positive number, it blocks at most 'timeout' seconds and raises
110 the Full exception if no free slot was available within that time.
111 Otherwise ('block' is false), put an item on the queue if a free slot
112 is immediately available, else raise the Full exception ('timeout'
113 is ignored in that case).
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000114 """
Tim Peters5af0e412004-07-12 00:45:14 +0000115 self.not_full.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000116 try:
Tim Peters71ed2202004-07-12 01:20:32 +0000117 if not block:
118 if self._full():
119 raise Full
120 elif timeout is None:
Tim Peters5af0e412004-07-12 00:45:14 +0000121 while self._full():
122 self.not_full.wait()
123 else:
124 if timeout < 0:
125 raise ValueError("'timeout' must be a positive number")
126 endtime = _time() + timeout
127 while self._full():
128 remaining = endtime - _time()
Tim Peters71ed2202004-07-12 01:20:32 +0000129 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +0000130 raise Full
131 self.not_full.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000132 self._put(item)
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000133 self.unfinished_tasks += 1
Tim Peters5af0e412004-07-12 00:45:14 +0000134 self.not_empty.notify()
Mark Hammond3b959db2002-04-19 00:11:32 +0000135 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000136 self.not_full.release()
Barry Warsaw3d96d521997-11-20 19:56:38 +0000137
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000138 def put_nowait(self, item):
139 """Put an item into the queue without blocking.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000140
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000141 Only enqueue the item if a free slot is immediately available.
142 Otherwise raise the Full exception.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000143 """
Tim Peters71ed2202004-07-12 01:20:32 +0000144 return self.put(item, False)
Barry Warsaw3d96d521997-11-20 19:56:38 +0000145
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000146 def get(self, block=True, timeout=None):
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000147 """Remove and return an item from the queue.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000148
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000149 If optional args 'block' is true and 'timeout' is None (the default),
150 block if necessary until an item is available. If 'timeout' is
151 a positive number, it blocks at most 'timeout' seconds and raises
152 the Empty exception if no item was available within that time.
153 Otherwise ('block' is false), return an item if one is immediately
154 available, else raise the Empty exception ('timeout' is ignored
155 in that case).
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 """
Tim Peters5af0e412004-07-12 00:45:14 +0000157 self.not_empty.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000158 try:
Tim Peters71ed2202004-07-12 01:20:32 +0000159 if not block:
160 if self._empty():
161 raise Empty
162 elif timeout is None:
Tim Peters5af0e412004-07-12 00:45:14 +0000163 while self._empty():
164 self.not_empty.wait()
165 else:
166 if timeout < 0:
167 raise ValueError("'timeout' must be a positive number")
168 endtime = _time() + timeout
169 while self._empty():
170 remaining = endtime - _time()
Tim Peters71ed2202004-07-12 01:20:32 +0000171 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +0000172 raise Empty
173 self.not_empty.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000174 item = self._get()
Tim Peters5af0e412004-07-12 00:45:14 +0000175 self.not_full.notify()
176 return item
Mark Hammond3b959db2002-04-19 00:11:32 +0000177 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000178 self.not_empty.release()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000179
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000180 def get_nowait(self):
181 """Remove and return an item from the queue without blocking.
Guido van Rossum9022fce1992-08-25 12:30:44 +0000182
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000183 Only get an item if one is immediately available. Otherwise
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000184 raise the Empty exception.
185 """
Tim Peters71ed2202004-07-12 01:20:32 +0000186 return self.get(False)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000187
Barry Warsaw3d96d521997-11-20 19:56:38 +0000188 # Override these methods to implement other queue organizations
189 # (e.g. stack or priority queue).
190 # These will only be called with appropriate locks held
Guido van Rossum9022fce1992-08-25 12:30:44 +0000191
Barry Warsaw3d96d521997-11-20 19:56:38 +0000192 # Initialize the queue representation
193 def _init(self, maxsize):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 self.maxsize = maxsize
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000195 self.queue = deque()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000196
Barry Warsaw3d96d521997-11-20 19:56:38 +0000197 def _qsize(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 return len(self.queue)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000199
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000200 # Check whether the queue is empty
Barry Warsaw3d96d521997-11-20 19:56:38 +0000201 def _empty(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 return not self.queue
Guido van Rossum9022fce1992-08-25 12:30:44 +0000203
Barry Warsaw3d96d521997-11-20 19:56:38 +0000204 # Check whether the queue is full
205 def _full(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 return self.maxsize > 0 and len(self.queue) == self.maxsize
Guido van Rossum9022fce1992-08-25 12:30:44 +0000207
Barry Warsaw3d96d521997-11-20 19:56:38 +0000208 # Put a new item in the queue
209 def _put(self, item):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 self.queue.append(item)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000211
Barry Warsaw3d96d521997-11-20 19:56:38 +0000212 # Get an item from the queue
213 def _get(self):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000214 return self.queue.popleft()