blob: c6c608b7440ce052960ebe451ff6ff8cc8ac8d00 [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)
Guido van Rossum9022fce1992-08-25 12:30:44 +000038
Barry Warsaw3d96d521997-11-20 19:56:38 +000039 def qsize(self):
Guido van Rossum9e1721f1999-02-08 18:34:01 +000040 """Return the approximate size of the queue (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000041 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 n = self._qsize()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000043 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000044 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000045
46 def empty(self):
Martin v. Löwis77ac4292002-10-15 15:11:13 +000047 """Return True if the queue is empty, False otherwise (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000048 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000049 n = self._empty()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000050 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000051 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000052
53 def full(self):
Martin v. Löwis77ac4292002-10-15 15:11:13 +000054 """Return True if the queue is full, False otherwise (not reliable!)."""
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000055 self.mutex.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 n = self._full()
Guido van Rossum7e6d18c1998-04-29 14:29:32 +000057 self.mutex.release()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 return n
Barry Warsaw3d96d521997-11-20 19:56:38 +000059
Martin v. Löwis77ac4292002-10-15 15:11:13 +000060 def put(self, item, block=True, timeout=None):
Guido van Rossumc09e6b11998-04-09 14:25:32 +000061 """Put an item into the queue.
62
Martin v. Löwis77ac4292002-10-15 15:11:13 +000063 If optional args 'block' is true and 'timeout' is None (the default),
64 block if necessary until a free slot is available. If 'timeout' is
65 a positive number, it blocks at most 'timeout' seconds and raises
66 the Full exception if no free slot was available within that time.
67 Otherwise ('block' is false), put an item on the queue if a free slot
68 is immediately available, else raise the Full exception ('timeout'
69 is ignored in that case).
Guido van Rossum9e1721f1999-02-08 18:34:01 +000070 """
Tim Peters5af0e412004-07-12 00:45:14 +000071 self.not_full.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +000072 try:
Tim Peters71ed2202004-07-12 01:20:32 +000073 if not block:
74 if self._full():
75 raise Full
76 elif timeout is None:
Tim Peters5af0e412004-07-12 00:45:14 +000077 while self._full():
78 self.not_full.wait()
79 else:
80 if timeout < 0:
81 raise ValueError("'timeout' must be a positive number")
82 endtime = _time() + timeout
83 while self._full():
84 remaining = endtime - _time()
Tim Peters71ed2202004-07-12 01:20:32 +000085 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +000086 raise Full
87 self.not_full.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +000088 self._put(item)
Tim Peters5af0e412004-07-12 00:45:14 +000089 self.not_empty.notify()
Mark Hammond3b959db2002-04-19 00:11:32 +000090 finally:
Tim Peters5af0e412004-07-12 00:45:14 +000091 self.not_full.release()
Barry Warsaw3d96d521997-11-20 19:56:38 +000092
Guido van Rossum9e1721f1999-02-08 18:34:01 +000093 def put_nowait(self, item):
94 """Put an item into the queue without blocking.
Guido van Rossumc09e6b11998-04-09 14:25:32 +000095
Guido van Rossum9e1721f1999-02-08 18:34:01 +000096 Only enqueue the item if a free slot is immediately available.
97 Otherwise raise the Full exception.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000098 """
Tim Peters71ed2202004-07-12 01:20:32 +000099 return self.put(item, False)
Barry Warsaw3d96d521997-11-20 19:56:38 +0000100
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000101 def get(self, block=True, timeout=None):
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000102 """Remove and return an item from the queue.
Guido van Rossumc09e6b11998-04-09 14:25:32 +0000103
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000104 If optional args 'block' is true and 'timeout' is None (the default),
105 block if necessary until an item is available. If 'timeout' is
106 a positive number, it blocks at most 'timeout' seconds and raises
107 the Empty exception if no item was available within that time.
108 Otherwise ('block' is false), return an item if one is immediately
109 available, else raise the Empty exception ('timeout' is ignored
110 in that case).
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 """
Tim Peters5af0e412004-07-12 00:45:14 +0000112 self.not_empty.acquire()
Mark Hammond3b959db2002-04-19 00:11:32 +0000113 try:
Tim Peters71ed2202004-07-12 01:20:32 +0000114 if not block:
115 if self._empty():
116 raise Empty
117 elif timeout is None:
Tim Peters5af0e412004-07-12 00:45:14 +0000118 while self._empty():
119 self.not_empty.wait()
120 else:
121 if timeout < 0:
122 raise ValueError("'timeout' must be a positive number")
123 endtime = _time() + timeout
124 while self._empty():
125 remaining = endtime - _time()
Tim Peters71ed2202004-07-12 01:20:32 +0000126 if remaining <= 0.0:
Tim Peters5af0e412004-07-12 00:45:14 +0000127 raise Empty
128 self.not_empty.wait(remaining)
Mark Hammond3b959db2002-04-19 00:11:32 +0000129 item = self._get()
Tim Peters5af0e412004-07-12 00:45:14 +0000130 self.not_full.notify()
131 return item
Mark Hammond3b959db2002-04-19 00:11:32 +0000132 finally:
Tim Peters5af0e412004-07-12 00:45:14 +0000133 self.not_empty.release()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000134
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000135 def get_nowait(self):
136 """Remove and return an item from the queue without blocking.
Guido van Rossum9022fce1992-08-25 12:30:44 +0000137
Martin v. Löwis77ac4292002-10-15 15:11:13 +0000138 Only get an item if one is immediately available. Otherwise
Guido van Rossum9e1721f1999-02-08 18:34:01 +0000139 raise the Empty exception.
140 """
Tim Peters71ed2202004-07-12 01:20:32 +0000141 return self.get(False)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000142
Barry Warsaw3d96d521997-11-20 19:56:38 +0000143 # Override these methods to implement other queue organizations
144 # (e.g. stack or priority queue).
145 # These will only be called with appropriate locks held
Guido van Rossum9022fce1992-08-25 12:30:44 +0000146
Barry Warsaw3d96d521997-11-20 19:56:38 +0000147 # Initialize the queue representation
148 def _init(self, maxsize):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000149 self.maxsize = maxsize
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000150 self.queue = deque()
Guido van Rossum9022fce1992-08-25 12:30:44 +0000151
Barry Warsaw3d96d521997-11-20 19:56:38 +0000152 def _qsize(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000153 return len(self.queue)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000154
Jeremy Hyltona05e2932000-06-28 14:48:01 +0000155 # Check whether the queue is empty
Barry Warsaw3d96d521997-11-20 19:56:38 +0000156 def _empty(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 return not self.queue
Guido van Rossum9022fce1992-08-25 12:30:44 +0000158
Barry Warsaw3d96d521997-11-20 19:56:38 +0000159 # Check whether the queue is full
160 def _full(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 return self.maxsize > 0 and len(self.queue) == self.maxsize
Guido van Rossum9022fce1992-08-25 12:30:44 +0000162
Barry Warsaw3d96d521997-11-20 19:56:38 +0000163 # Put a new item in the queue
164 def _put(self, item):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000165 self.queue.append(item)
Guido van Rossum9022fce1992-08-25 12:30:44 +0000166
Barry Warsaw3d96d521997-11-20 19:56:38 +0000167 # Get an item from the queue
168 def _get(self):
Raymond Hettinger756b3f32004-01-29 06:37:52 +0000169 return self.queue.popleft()