queue.py 11.1 KB
Newer Older
1
'''A multi-producer, multi-consumer queue.'''
2

3
import threading
4
from collections import deque
5
from heapq import heappush, heappop
6
from time import monotonic as time
7 8 9 10
try:
    from _queue import SimpleQueue
except ImportError:
    SimpleQueue = None
11

12
__all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue', 'SimpleQueue']
Brett Cannon's avatar
Brett Cannon committed
13

14 15 16 17 18 19 20

try:
    from _queue import Empty
except AttributeError:
    class Empty(Exception):
        'Exception raised by Queue.get(block=0)/get_nowait().'
        pass
21 22

class Full(Exception):
23
    'Exception raised by Queue.put(block=0)/put_nowait().'
24
    pass
25

26

27
class Queue:
28
    '''Create a queue object with a given maximum size.
29

30
    If maxsize is <= 0, the queue size is infinite.
31 32
    '''

33
    def __init__(self, maxsize=0):
34
        self.maxsize = maxsize
35
        self._init(maxsize)
36

37 38
        # mutex must be held whenever the queue is mutating.  All methods
        # that acquire mutex must release it before returning.  mutex
39
        # is shared between the three conditions, so acquiring and
40
        # releasing the conditions also acquires and releases mutex.
41
        self.mutex = threading.Lock()
42

43 44
        # Notify not_empty whenever an item is added to the queue; a
        # thread waiting to get is notified then.
45
        self.not_empty = threading.Condition(self.mutex)
46

47 48
        # Notify not_full whenever an item is removed from the queue;
        # a thread waiting to put is notified then.
49
        self.not_full = threading.Condition(self.mutex)
50

51 52
        # Notify all_tasks_done whenever the number of unfinished tasks
        # drops to zero; thread waiting to join() is notified to resume
53
        self.all_tasks_done = threading.Condition(self.mutex)
54 55 56
        self.unfinished_tasks = 0

    def task_done(self):
57
        '''Indicate that a formerly enqueued task is complete.
58 59 60 61 62 63 64 65 66 67 68

        Used by Queue consumer threads.  For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items
        have been processed (meaning that a task_done() call was received
        for every item that had been put() into the queue).

        Raises a ValueError if called more times than there were items
        placed in the queue.
69
        '''
70
        with self.all_tasks_done:
71 72 73 74
            unfinished = self.unfinished_tasks - 1
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError('task_done() called too many times')
75
                self.all_tasks_done.notify_all()
76 77 78
            self.unfinished_tasks = unfinished

    def join(self):
79
        '''Blocks until all items in the Queue have been gotten and processed.
80 81 82 83 84 85

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer thread calls task_done()
        to indicate the item was retrieved and all work on it is complete.

        When the count of unfinished tasks drops to zero, join() unblocks.
86
        '''
87
        with self.all_tasks_done:
88 89
            while self.unfinished_tasks:
                self.all_tasks_done.wait()
90 91

    def qsize(self):
92
        '''Return the approximate size of the queue (not reliable!).'''
93 94
        with self.mutex:
            return self._qsize()
95

96
    def empty(self):
97
        '''Return True if the queue is empty, False otherwise (not reliable!).
98 99 100 101 102 103 104 105

        This method is likely to be removed at some point.  Use qsize() == 0
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can grow before the result of empty() or
        qsize() can be used.

        To create code that needs to wait for all queued tasks to be
        completed, the preferred technique is to use the join() method.
106
        '''
107 108
        with self.mutex:
            return not self._qsize()
109 110

    def full(self):
111
        '''Return True if the queue is full, False otherwise (not reliable!).
112

113
        This method is likely to be removed at some point.  Use qsize() >= n
114 115 116
        as a direct substitute, but be aware that either approach risks a race
        condition where a queue can shrink before the result of full() or
        qsize() can be used.
117
        '''
118 119
        with self.mutex:
            return 0 < self.maxsize <= self._qsize()
120

121
    def put(self, item, block=True, timeout=None):
122
        '''Put an item into the queue.
123

124 125
        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until a free slot is available. If 'timeout' is
126
        a non-negative number, it blocks at most 'timeout' seconds and raises
127 128 129 130
        the Full exception if no free slot was available within that time.
        Otherwise ('block' is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception ('timeout'
        is ignored in that case).
131
        '''
132
        with self.not_full:
133 134
            if self.maxsize > 0:
                if not block:
135
                    if self._qsize() >= self.maxsize:
136 137
                        raise Full
                elif timeout is None:
138
                    while self._qsize() >= self.maxsize:
139
                        self.not_full.wait()
140
                elif timeout < 0:
141
                    raise ValueError("'timeout' must be a non-negative number")
142
                else:
143
                    endtime = time() + timeout
144
                    while self._qsize() >= self.maxsize:
145
                        remaining = endtime - time()
146 147 148
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
149
            self._put(item)
150
            self.unfinished_tasks += 1
151
            self.not_empty.notify()
152

153
    def get(self, block=True, timeout=None):
154
        '''Remove and return an item from the queue.
155

156 157
        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until an item is available. If 'timeout' is
158
        a non-negative number, it blocks at most 'timeout' seconds and raises
159 160 161 162
        the Empty exception if no item was available within that time.
        Otherwise ('block' is false), return an item if one is immediately
        available, else raise the Empty exception ('timeout' is ignored
        in that case).
163
        '''
164
        with self.not_empty:
165
            if not block:
166
                if not self._qsize():
167 168
                    raise Empty
            elif timeout is None:
169
                while not self._qsize():
170
                    self.not_empty.wait()
171
            elif timeout < 0:
172
                raise ValueError("'timeout' must be a non-negative number")
173
            else:
174
                endtime = time() + timeout
175
                while not self._qsize():
176
                    remaining = endtime - time()
177
                    if remaining <= 0.0:
178
                        raise Empty
179
                    self.not_empty.wait(remaining)
180
            item = self._get()
181 182
            self.not_full.notify()
            return item
183

184
    def put_nowait(self, item):
185
        '''Put an item into the queue without blocking.
186 187 188

        Only enqueue the item if a free slot is immediately available.
        Otherwise raise the Full exception.
189
        '''
190 191
        return self.put(item, block=False)

Guido van Rossum's avatar
Guido van Rossum committed
192
    def get_nowait(self):
193
        '''Remove and return an item from the queue without blocking.
194

195
        Only get an item if one is immediately available. Otherwise
Guido van Rossum's avatar
Guido van Rossum committed
196
        raise the Empty exception.
197
        '''
198
        return self.get(block=False)
199 200 201 202 203 204 205

    # Override these methods to implement other queue organizations
    # (e.g. stack or priority queue).
    # These will only be called with appropriate locks held

    # Initialize the queue representation
    def _init(self, maxsize):
206
        self.queue = deque()
207

208
    def _qsize(self):
209
        return len(self.queue)
210 211 212

    # Put a new item in the queue
    def _put(self, item):
213
        self.queue.append(item)
214 215 216

    # Get an item from the queue
    def _get(self):
217
        return self.queue.popleft()
218 219 220 221 222 223 224 225 226 227 228


class PriorityQueue(Queue):
    '''Variant of Queue that retrieves open entries in priority order (lowest first).

    Entries are typically tuples of the form:  (priority number, data).
    '''

    def _init(self, maxsize):
        self.queue = []

229
    def _qsize(self):
230 231
        return len(self.queue)

232
    def _put(self, item):
233 234
        heappush(self.queue, item)

235
    def _get(self):
236 237 238 239 240 241 242 243 244
        return heappop(self.queue)


class LifoQueue(Queue):
    '''Variant of Queue that retrieves most recently added entries first.'''

    def _init(self, maxsize):
        self.queue = []

245
    def _qsize(self):
246 247 248 249 250 251 252
        return len(self.queue)

    def _put(self, item):
        self.queue.append(item)

    def _get(self):
        return self.queue.pop()
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321


class _PySimpleQueue:
    '''Simple, unbounded FIFO queue.

    This pure Python implementation is not reentrant.
    '''
    # Note: while this pure Python version provides fairness
    # (by using a threading.Semaphore which is itself fair, being based
    #  on threading.Condition), fairness is not part of the API contract.
    # This allows the C version to use a different implementation.

    def __init__(self):
        self._queue = deque()
        self._count = threading.Semaphore(0)

    def put(self, item, block=True, timeout=None):
        '''Put the item on the queue.

        The optional 'block' and 'timeout' arguments are ignored, as this method
        never blocks.  They are provided for compatibility with the Queue class.
        '''
        self._queue.append(item)
        self._count.release()

    def get(self, block=True, timeout=None):
        '''Remove and return an item from the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until an item is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Empty exception if no item was available within that time.
        Otherwise ('block' is false), return an item if one is immediately
        available, else raise the Empty exception ('timeout' is ignored
        in that case).
        '''
        if timeout is not None and timeout < 0:
            raise ValueError("'timeout' must be a non-negative number")
        if not self._count.acquire(block, timeout):
            raise Empty
        return self._queue.popleft()

    def put_nowait(self, item):
        '''Put an item into the queue without blocking.

        This is exactly equivalent to `put(item)` and is only provided
        for compatibility with the Queue class.
        '''
        return self.put(item, block=False)

    def get_nowait(self):
        '''Remove and return an item from the queue without blocking.

        Only get an item if one is immediately available. Otherwise
        raise the Empty exception.
        '''
        return self.get(block=False)

    def empty(self):
        '''Return True if the queue is empty, False otherwise (not reliable!).'''
        return len(self._queue) == 0

    def qsize(self):
        '''Return the approximate size of the queue (not reliable!).'''
        return len(self._queue)


if SimpleQueue is None:
    SimpleQueue = _PySimpleQueue