blob: f8aa0af23180ab82b9e060435602a49ed659dd80 [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:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017 """Create a queue object with a given maximum size.
Guido van Rossum9022fce1992-08-25 12:30:44 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 Hettingerda3caed2008-01-14 21:39:24 +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
Thomas Wouters89f507f2006-12-13 04:49:30 +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)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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:
60 unfinished = self.unfinished_tasks - 1
61 if unfinished <= 0:
62 if unfinished < 0:
63 raise ValueError('task_done() called too many times')
64 self.all_tasks_done.notifyAll()
65 self.unfinished_tasks = unfinished
66 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
Martin v. Löwis77ac4292002-10-15 15:11:13 +000092 def put(self, item, block=True, timeout=None):
Guido van Rossumc09e6b11998-04-09 14:25:32 +000093 """Put an item into the queue.
94
Martin v. Löwis77ac4292002-10-15 15:11:13 +000095 If optional args 'block' is true and 'timeout' is None (the default),
96 block if necessary until a free slot is available. If 'timeout' is
97 a positive number, it blocks at most 'timeout' seconds and raises
98 the Full exception if no free slot was available within that time.
99 Otherwise ('block' is false), put an item on the queue if a free slot
100 is immediately available, else raise the Full exception ('timeout'
101 is ignored in that case).
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000102 """
Tim Peters5af0e412004-07-12 00:45:14 +0000103 self.not_full.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000104 try:
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000105 if self.maxsize > 0:
106 if not block:
107 if self._qsize() == self.maxsize:
108 raise Full
109 elif timeout is None:
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000110 while self._qsize() == self.maxsize:
111 self.not_full.wait()
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000112 elif timeout < 0:
Tim Peters5af0e412004-07-12 00:45:14 +0000113 raise ValueError("'timeout' must be a positive number")
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000114 else:
115 endtime = _time() + timeout
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000116 while self._qsize() == self.maxsize:
117 remaining = endtime - _time()
118 if remaining <= 0.0:
119 raise Full
120 self.not_full.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000121 self._put(item)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000122 self.unfinished_tasks += 1
Tim Peters5af0e412004-07-12 00:45:14 +0000123 self.not_empty.notify()
Mark Hammond3b959db2002-04-19 00:11:32 +0000124 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000125 self.not_full.release()
Barry Warsaw3d96d521997-11-20 19:56:38 +0000126
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000127 def put_nowait(self, item):
128 """Put an item into the queue without blocking.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000129
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000130 Only enqueue the item if a free slot is immediately available.
131 Otherwise raise the Full exception.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000132 """
Tim Peters71ed2202004-07-12 01:20:32 +0000133 return self.put(item, False)
Barry Warsaw3d96d521997-11-20 19:56:38 +0000134
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000135 def get(self, block=True, timeout=None):
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000136 """Remove and return an item from the queue.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000137
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000138 If optional args 'block' is true and 'timeout' is None (the default),
139 block if necessary until an item is available. If 'timeout' is
140 a positive number, it blocks at most 'timeout' seconds and raises
141 the Empty exception if no item was available within that time.
142 Otherwise ('block' is false), return an item if one is immediately
143 available, else raise the Empty exception ('timeout' is ignored
144 in that case).
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 """
Tim Peters5af0e412004-07-12 00:45:14 +0000146 self.not_empty.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000147 try:
Tim Peters71ed2202004-07-12 01:20:32 +0000148 if not block:
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000149 if not self._qsize():
Tim Peters71ed2202004-07-12 01:20:32 +0000150 raise Empty
151 elif timeout is None:
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000152 while not self._qsize():
Tim Peters5af0e412004-07-12 00:45:14 +0000153 self.not_empty.wait()
Raymond Hettingerae138cb2008-01-15 20:42:00 +0000154 elif timeout < 0:
155 raise ValueError("'timeout' must be a positive number")
Tim Peters5af0e412004-07-12 00:45:14 +0000156 else:
Tim Peters5af0e412004-07-12 00:45:14 +0000157 endtime = _time() + timeout
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000158 while not self._qsize():
Tim Peters5af0e412004-07-12 00:45:14 +0000159 remaining = endtime - _time()
Tim Peters71ed2202004-07-12 01:20:32 +0000160 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +0000161 raise Empty
162 self.not_empty.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000163 item = self._get()
Tim Peters5af0e412004-07-12 00:45:14 +0000164 self.not_full.notify()
165 return item
Mark Hammond3b959db2002-04-19 00:11:32 +0000166 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000167 self.not_empty.release()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000168
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000169 def get_nowait(self):
170 """Remove and return an item from the queue without blocking.
Guido van Rossum9022fce1992-08-25 12:30:44 +0000171
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000172 Only get an item if one is immediately available. Otherwise
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000173 raise the Empty exception.
174 """
Tim Peters71ed2202004-07-12 01:20:32 +0000175 return self.get(False)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000176
Barry Warsaw3d96d521997-11-20 19:56:38 +0000177 # Override these methods to implement other queue organizations
178 # (e.g. stack or priority queue).
179 # These will only be called with appropriate locks held
Guido van Rossum9022fce1992-08-25 12:30:44 +0000180
Barry Warsaw3d96d521997-11-20 19:56:38 +0000181 # Initialize the queue representation
182 def _init(self, maxsize):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000183 self.queue = deque()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000184
Barry Warsaw3d96d521997-11-20 19:56:38 +0000185 def _qsize(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 return len(self.queue)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000187
Barry Warsaw3d96d521997-11-20 19:56:38 +0000188 # Put a new item in the queue
189 def _put(self, item):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 self.queue.append(item)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000191
Barry Warsaw3d96d521997-11-20 19:56:38 +0000192 # Get an item from the queue
193 def _get(self):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000194 return self.queue.popleft()