blob: ce340249b2b67e3708e61d412dd88cde3d68b122 [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:
Skip Montanaro86116e22006-06-10 14:09:11 +000017 """Create a queue object with a given maximum size.
Guido van Rossum9022fce1992-08-25 12:30:44 +000018
Skip Montanaro86116e22006-06-10 14:09:11 +000019 If maxsize is <= 0, the queue size is infinite.
20 """
21 def __init__(self, maxsize=0):
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
Raymond Hettingerf59e9622008-01-15 20:52:42 +000026 self.maxsize = maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000027 self._init(maxsize)
Tim Peters5af0e412004-07-12 00:45:14 +000028 # mutex must be held whenever the queue is mutating. All methods
29 # that acquire mutex must release it before returning. mutex
Raymond Hettingera3c77672006-11-23 21:35:19 +000030 # is shared between the three conditions, so acquiring and
Tim Peters5af0e412004-07-12 00:45:14 +000031 # releasing the conditions also acquires and releases mutex.
32 self.mutex = threading.Lock()
33 # Notify not_empty whenever an item is added to the queue; a
34 # thread waiting to get is notified then.
35 self.not_empty = threading.Condition(self.mutex)
36 # Notify not_full whenever an item is removed from the queue;
37 # a thread waiting to put is notified then.
38 self.not_full = threading.Condition(self.mutex)
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +000039 # Notify all_tasks_done whenever the number of unfinished tasks
40 # drops to zero; thread waiting to join() is notified to resume
41 self.all_tasks_done = threading.Condition(self.mutex)
42 self.unfinished_tasks = 0
43
44 def task_done(self):
45 """Indicate that a formerly enqueued task is complete.
46
47 Used by Queue consumer threads. For each get() used to fetch a task,
48 a subsequent call to task_done() tells the queue that the processing
49 on the task is complete.
50
51 If a join() is currently blocking, it will resume when all items
52 have been processed (meaning that a task_done() call was received
53 for every item that had been put() into the queue).
54
55 Raises a ValueError if called more times than there were items
56 placed in the queue.
57 """
58 self.all_tasks_done.acquire()
59 try:
Raymond Hettingerc4e94b92006-03-25 12:15:04 +000060 unfinished = self.unfinished_tasks - 1
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +000061 if unfinished <= 0:
62 if unfinished < 0:
Tim Peterse33901e2006-03-25 01:50:43 +000063 raise ValueError('task_done() called too many times')
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +000064 self.all_tasks_done.notifyAll()
Raymond Hettingerc4e94b92006-03-25 12:15:04 +000065 self.unfinished_tasks = unfinished
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +000066 finally:
67 self.all_tasks_done.release()
68
69 def join(self):
70 """Blocks until all items in the Queue have been gotten and processed.
71
72 The count of unfinished tasks goes up whenever an item is added to the
73 queue. The count goes down whenever a consumer thread calls task_done()
74 to indicate the item was retrieved and all work on it is complete.
75
76 When the count of unfinished tasks drops to zero, join() unblocks.
77 """
78 self.all_tasks_done.acquire()
79 try:
80 while self.unfinished_tasks:
81 self.all_tasks_done.wait()
82 finally:
83 self.all_tasks_done.release()
Guido van Rossum9022fce1992-08-25 12:30:44 +000084
Barry Warsaw3d96d521997-11-20 19:56:38 +000085 def qsize(self):
Guido van Rossum9e1721f1999-02-08 18:34:01 +000086 """Return the approximate size of the queue (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000087 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 n = self._qsize()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000089 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000090 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000091
92 def empty(self):
Martin v. Löwis77ac4292002-10-15 15:11:13 +000093 """Return True if the queue is empty, False otherwise (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000094 self.mutex.acquire()
Raymond Hettingerf59e9622008-01-15 20:52:42 +000095 n = not self._qsize()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000096 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000098
99 def full(self):
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000100 """Return True if the queue is full, False otherwise (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +0000101 self.mutex.acquire()
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000102 n = 0 < self.maxsize == self._qsize()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +0000103 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000104 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +0000105
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000106 def put(self, item, block=True, timeout=None):
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000107 """Put an item into the queue.
108
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000109 If optional args 'block' is true and 'timeout' is None (the default),
110 block if necessary until a free slot is available. If 'timeout' is
111 a positive number, it blocks at most 'timeout' seconds and raises
112 the Full exception if no free slot was available within that time.
113 Otherwise ('block' is false), put an item on the queue if a free slot
114 is immediately available, else raise the Full exception ('timeout'
115 is ignored in that case).
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000116 """
Tim Peters5af0e412004-07-12 00:45:14 +0000117 self.not_full.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000118 try:
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000119 if self.maxsize > 0:
120 if not block:
121 if self._qsize() == self.maxsize:
Tim Peters5af0e412004-07-12 00:45:14 +0000122 raise Full
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000123 elif timeout is None:
124 while self._qsize() == self.maxsize:
125 self.not_full.wait()
126 elif timeout < 0:
127 raise ValueError("'timeout' must be a positive number")
128 else:
129 endtime = _time() + timeout
130 while self._qsize() == self.maxsize:
131 remaining = endtime - _time()
132 if remaining <= 0.0:
133 raise Full
134 self.not_full.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000135 self._put(item)
Raymond Hettingerfd3fcf02006-03-24 20:43:29 +0000136 self.unfinished_tasks += 1
Tim Peters5af0e412004-07-12 00:45:14 +0000137 self.not_empty.notify()
Mark Hammond3b959db2002-04-19 00:11:32 +0000138 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000139 self.not_full.release()
Barry Warsaw3d96d521997-11-20 19:56:38 +0000140
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000141 def put_nowait(self, item):
142 """Put an item into the queue without blocking.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000143
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000144 Only enqueue the item if a free slot is immediately available.
145 Otherwise raise the Full exception.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 """
Tim Peters71ed2202004-07-12 01:20:32 +0000147 return self.put(item, False)
Barry Warsaw3d96d521997-11-20 19:56:38 +0000148
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000149 def get(self, block=True, timeout=None):
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000150 """Remove and return an item from the queue.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000151
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000152 If optional args 'block' is true and 'timeout' is None (the default),
153 block if necessary until an item is available. If 'timeout' is
154 a positive number, it blocks at most 'timeout' seconds and raises
155 the Empty exception if no item was available within that time.
156 Otherwise ('block' is false), return an item if one is immediately
157 available, else raise the Empty exception ('timeout' is ignored
158 in that case).
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000159 """
Tim Peters5af0e412004-07-12 00:45:14 +0000160 self.not_empty.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000161 try:
Tim Peters71ed2202004-07-12 01:20:32 +0000162 if not block:
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000163 if not self._qsize():
Tim Peters71ed2202004-07-12 01:20:32 +0000164 raise Empty
165 elif timeout is None:
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000166 while not self._qsize():
Tim Peters5af0e412004-07-12 00:45:14 +0000167 self.not_empty.wait()
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000168 elif timeout < 0:
169 raise ValueError("'timeout' must be a positive number")
Tim Peters5af0e412004-07-12 00:45:14 +0000170 else:
Tim Peters5af0e412004-07-12 00:45:14 +0000171 endtime = _time() + timeout
Raymond Hettingerf59e9622008-01-15 20:52:42 +0000172 while not self._qsize():
Tim Peters5af0e412004-07-12 00:45:14 +0000173 remaining = endtime - _time()
Tim Peters71ed2202004-07-12 01:20:32 +0000174 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +0000175 raise Empty
176 self.not_empty.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000177 item = self._get()
Tim Peters5af0e412004-07-12 00:45:14 +0000178 self.not_full.notify()
179 return item
Mark Hammond3b959db2002-04-19 00:11:32 +0000180 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000181 self.not_empty.release()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000182
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000183 def get_nowait(self):
184 """Remove and return an item from the queue without blocking.
Guido van Rossum9022fce1992-08-25 12:30:44 +0000185
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000186 Only get an item if one is immediately available. Otherwise
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000187 raise the Empty exception.
188 """
Tim Peters71ed2202004-07-12 01:20:32 +0000189 return self.get(False)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000190
Barry Warsaw3d96d521997-11-20 19:56:38 +0000191 # Override these methods to implement other queue organizations
192 # (e.g. stack or priority queue).
193 # These will only be called with appropriate locks held
Guido van Rossum9022fce1992-08-25 12:30:44 +0000194
Barry Warsaw3d96d521997-11-20 19:56:38 +0000195 # Initialize the queue representation
196 def _init(self, maxsize):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000197 self.queue = deque()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000198
Barry Warsaw3d96d521997-11-20 19:56:38 +0000199 def _qsize(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 return len(self.queue)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000201
Barry Warsaw3d96d521997-11-20 19:56:38 +0000202 # Put a new item in the queue
203 def _put(self, item):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 self.queue.append(item)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000205
Barry Warsaw3d96d521997-11-20 19:56:38 +0000206 # Get an item from the queue
207 def _get(self):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000208 return self.queue.popleft()