blob: c4f9cda4998f96048a9ecef43165f6e97380eca2 [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module implementing queues
3#
4# multiprocessing/queues.py
5#
R. David Murray3fc969a2010-12-14 01:38:16 +00006# Copyright (c) 2006-2008, R Oudkerk
7# All rights reserved.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12#
13# 1. Redistributions of source code must retain the above copyright
14# notice, this list of conditions and the following disclaimer.
15# 2. Redistributions in binary form must reproduce the above copyright
16# notice, this list of conditions and the following disclaimer in the
17# documentation and/or other materials provided with the distribution.
18# 3. Neither the name of author nor the names of any contributors may be
19# used to endorse or promote products derived from this software
20# without specific prior written permission.
21#
22# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
23# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32# SUCH DAMAGE.
Benjamin Petersone711caf2008-06-11 16:44:04 +000033#
34
Jesse Noller14f3ae22009-03-31 03:37:07 +000035__all__ = ['Queue', 'SimpleQueue', 'JoinableQueue']
Benjamin Petersone711caf2008-06-11 16:44:04 +000036
37import sys
38import os
39import threading
40import collections
41import time
Benjamin Petersone711caf2008-06-11 16:44:04 +000042import weakref
Antoine Pitroudc19c242011-07-16 01:51:58 +020043import errno
Benjamin Petersone711caf2008-06-11 16:44:04 +000044
45from queue import Empty, Full
46import _multiprocessing
Antoine Pitroudd696492011-06-08 17:21:55 +020047from multiprocessing.connection import Pipe, SentinelReady
Benjamin Petersone711caf2008-06-11 16:44:04 +000048from multiprocessing.synchronize import Lock, BoundedSemaphore, Semaphore, Condition
49from multiprocessing.util import debug, info, Finalize, register_after_fork
50from multiprocessing.forking import assert_spawning
51
52#
53# Queue type using a pipe, buffer and thread
54#
55
56class Queue(object):
57
58 def __init__(self, maxsize=0):
59 if maxsize <= 0:
60 maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX
61 self._maxsize = maxsize
62 self._reader, self._writer = Pipe(duplex=False)
63 self._rlock = Lock()
64 self._opid = os.getpid()
65 if sys.platform == 'win32':
66 self._wlock = None
67 else:
68 self._wlock = Lock()
69 self._sem = BoundedSemaphore(maxsize)
Antoine Pitroudc19c242011-07-16 01:51:58 +020070 # For use by concurrent.futures
71 self._ignore_epipe = False
Benjamin Petersone711caf2008-06-11 16:44:04 +000072
73 self._after_fork()
74
75 if sys.platform != 'win32':
76 register_after_fork(self, Queue._after_fork)
77
78 def __getstate__(self):
79 assert_spawning(self)
Antoine Pitroufb960892011-07-20 02:01:39 +020080 return (self._ignore_epipe, self._maxsize, self._reader, self._writer,
Benjamin Petersone711caf2008-06-11 16:44:04 +000081 self._rlock, self._wlock, self._sem, self._opid)
82
83 def __setstate__(self, state):
Antoine Pitroufb960892011-07-20 02:01:39 +020084 (self._ignore_epipe, self._maxsize, self._reader, self._writer,
Benjamin Petersone711caf2008-06-11 16:44:04 +000085 self._rlock, self._wlock, self._sem, self._opid) = state
86 self._after_fork()
87
88 def _after_fork(self):
89 debug('Queue._after_fork()')
90 self._notempty = threading.Condition(threading.Lock())
91 self._buffer = collections.deque()
92 self._thread = None
93 self._jointhread = None
94 self._joincancelled = False
95 self._closed = False
96 self._close = None
97 self._send = self._writer.send
98 self._recv = self._reader.recv
99 self._poll = self._reader.poll
100
101 def put(self, obj, block=True, timeout=None):
102 assert not self._closed
103 if not self._sem.acquire(block, timeout):
104 raise Full
105
106 self._notempty.acquire()
107 try:
108 if self._thread is None:
109 self._start_thread()
110 self._buffer.append(obj)
111 self._notempty.notify()
112 finally:
113 self._notempty.release()
114
115 def get(self, block=True, timeout=None):
116 if block and timeout is None:
117 self._rlock.acquire()
118 try:
119 res = self._recv()
120 self._sem.release()
121 return res
122 finally:
123 self._rlock.release()
124
125 else:
126 if block:
127 deadline = time.time() + timeout
128 if not self._rlock.acquire(block, timeout):
129 raise Empty
130 try:
Antoine Pitroua3651132011-11-10 00:37:09 +0100131 if block:
132 timeout = deadline - time.time()
133 if timeout < 0 or not self._poll(timeout):
134 raise Empty
135 elif not self._poll():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000136 raise Empty
137 res = self._recv()
138 self._sem.release()
139 return res
140 finally:
141 self._rlock.release()
142
143 def qsize(self):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000144 # Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000145 return self._maxsize - self._sem._semlock._get_value()
146
147 def empty(self):
148 return not self._poll()
149
150 def full(self):
151 return self._sem._semlock._is_zero()
152
153 def get_nowait(self):
154 return self.get(False)
155
156 def put_nowait(self, obj):
157 return self.put(obj, False)
158
159 def close(self):
160 self._closed = True
161 self._reader.close()
162 if self._close:
163 self._close()
164
165 def join_thread(self):
166 debug('Queue.join_thread()')
167 assert self._closed
168 if self._jointhread:
169 self._jointhread()
170
171 def cancel_join_thread(self):
172 debug('Queue.cancel_join_thread()')
173 self._joincancelled = True
174 try:
175 self._jointhread.cancel()
176 except AttributeError:
177 pass
178
179 def _start_thread(self):
180 debug('Queue._start_thread()')
181
182 # Start thread which transfers data from buffer to pipe
183 self._buffer.clear()
184 self._thread = threading.Thread(
185 target=Queue._feed,
186 args=(self._buffer, self._notempty, self._send,
Antoine Pitroudc19c242011-07-16 01:51:58 +0200187 self._wlock, self._writer.close, self._ignore_epipe),
Benjamin Petersone711caf2008-06-11 16:44:04 +0000188 name='QueueFeederThread'
189 )
Benjamin Peterson72753702008-08-18 18:09:21 +0000190 self._thread.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000191
192 debug('doing self._thread.start()')
193 self._thread.start()
194 debug('... done self._thread.start()')
195
196 # On process exit we will wait for data to be flushed to pipe.
197 #
198 # However, if this process created the queue then all
199 # processes which use the queue will be descendants of this
200 # process. Therefore waiting for the queue to be flushed
201 # is pointless once all the child processes have been joined.
202 created_by_this_process = (self._opid == os.getpid())
203 if not self._joincancelled and not created_by_this_process:
204 self._jointhread = Finalize(
205 self._thread, Queue._finalize_join,
206 [weakref.ref(self._thread)],
207 exitpriority=-5
208 )
209
210 # Send sentinel to the thread queue object when garbage collected
211 self._close = Finalize(
212 self, Queue._finalize_close,
213 [self._buffer, self._notempty],
214 exitpriority=10
215 )
216
217 @staticmethod
218 def _finalize_join(twr):
219 debug('joining queue thread')
220 thread = twr()
221 if thread is not None:
222 thread.join()
223 debug('... queue thread joined')
224 else:
225 debug('... queue thread already dead')
226
227 @staticmethod
228 def _finalize_close(buffer, notempty):
229 debug('telling queue thread to quit')
230 notempty.acquire()
231 try:
232 buffer.append(_sentinel)
233 notempty.notify()
234 finally:
235 notempty.release()
236
237 @staticmethod
Antoine Pitroudc19c242011-07-16 01:51:58 +0200238 def _feed(buffer, notempty, send, writelock, close, ignore_epipe):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000239 debug('starting thread to feed data to pipe')
240 from .util import is_exiting
241
242 nacquire = notempty.acquire
243 nrelease = notempty.release
244 nwait = notempty.wait
245 bpopleft = buffer.popleft
246 sentinel = _sentinel
247 if sys.platform != 'win32':
248 wacquire = writelock.acquire
249 wrelease = writelock.release
250 else:
251 wacquire = None
252
253 try:
254 while 1:
255 nacquire()
256 try:
257 if not buffer:
258 nwait()
259 finally:
260 nrelease()
261 try:
262 while 1:
263 obj = bpopleft()
264 if obj is sentinel:
265 debug('feeder thread got sentinel -- exiting')
266 close()
267 return
268
269 if wacquire is None:
270 send(obj)
271 else:
272 wacquire()
273 try:
274 send(obj)
275 finally:
276 wrelease()
277 except IndexError:
278 pass
279 except Exception as e:
Antoine Pitroudc19c242011-07-16 01:51:58 +0200280 if ignore_epipe and getattr(e, 'errno', 0) == errno.EPIPE:
281 return
Benjamin Petersone711caf2008-06-11 16:44:04 +0000282 # Since this runs in a daemon thread the resources it uses
283 # may be become unusable while the process is cleaning up.
284 # We ignore errors which happen after the process has
285 # started to cleanup.
286 try:
287 if is_exiting():
288 info('error in queue thread: %s', e)
289 else:
290 import traceback
291 traceback.print_exc()
292 except Exception:
293 pass
294
295_sentinel = object()
296
297#
298# A queue type which also supports join() and task_done() methods
299#
300# Note that if you do not call task_done() for each finished task then
301# eventually the counter's semaphore may overflow causing Bad Things
302# to happen.
303#
304
305class JoinableQueue(Queue):
306
307 def __init__(self, maxsize=0):
308 Queue.__init__(self, maxsize)
309 self._unfinished_tasks = Semaphore(0)
310 self._cond = Condition()
311
312 def __getstate__(self):
313 return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks)
314
315 def __setstate__(self, state):
316 Queue.__setstate__(self, state[:-2])
317 self._cond, self._unfinished_tasks = state[-2:]
318
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000319 def put(self, obj, block=True, timeout=None):
320 assert not self._closed
321 if not self._sem.acquire(block, timeout):
322 raise Full
323
324 self._notempty.acquire()
325 self._cond.acquire()
326 try:
327 if self._thread is None:
328 self._start_thread()
329 self._buffer.append(obj)
330 self._unfinished_tasks.release()
331 self._notempty.notify()
332 finally:
333 self._cond.release()
334 self._notempty.release()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000335
336 def task_done(self):
337 self._cond.acquire()
338 try:
339 if not self._unfinished_tasks.acquire(False):
340 raise ValueError('task_done() called too many times')
341 if self._unfinished_tasks._semlock._is_zero():
342 self._cond.notify_all()
343 finally:
344 self._cond.release()
345
346 def join(self):
347 self._cond.acquire()
348 try:
349 if not self._unfinished_tasks._semlock._is_zero():
350 self._cond.wait()
351 finally:
352 self._cond.release()
353
354#
355# Simplified Queue type -- really just a locked pipe
356#
357
358class SimpleQueue(object):
359
360 def __init__(self):
361 self._reader, self._writer = Pipe(duplex=False)
362 self._rlock = Lock()
363 if sys.platform == 'win32':
364 self._wlock = None
365 else:
366 self._wlock = Lock()
367 self._make_methods()
368
369 def empty(self):
370 return not self._reader.poll()
371
372 def __getstate__(self):
373 assert_spawning(self)
374 return (self._reader, self._writer, self._rlock, self._wlock)
375
376 def __setstate__(self, state):
377 (self._reader, self._writer, self._rlock, self._wlock) = state
378 self._make_methods()
379
380 def _make_methods(self):
381 recv = self._reader.recv
382 racquire, rrelease = self._rlock.acquire, self._rlock.release
Antoine Pitroudd696492011-06-08 17:21:55 +0200383 def get(*, sentinels=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000384 racquire()
385 try:
Antoine Pitroudd696492011-06-08 17:21:55 +0200386 return recv(sentinels)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000387 finally:
388 rrelease()
389 self.get = get
390
391 if self._wlock is None:
392 # writes to a message oriented win32 pipe are atomic
393 self.put = self._writer.send
394 else:
395 send = self._writer.send
396 wacquire, wrelease = self._wlock.acquire, self._wlock.release
397 def put(obj):
398 wacquire()
399 try:
400 return send(obj)
401 finally:
402 wrelease()
403 self.put = put