blob: 51d991245c1ae28730378b2280a3181cd0dfc287 [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
42import atexit
43import weakref
44
45from queue import Empty, Full
46import _multiprocessing
47from multiprocessing import Pipe
48from 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)
70
71 self._after_fork()
72
73 if sys.platform != 'win32':
74 register_after_fork(self, Queue._after_fork)
75
76 def __getstate__(self):
77 assert_spawning(self)
78 return (self._maxsize, self._reader, self._writer,
79 self._rlock, self._wlock, self._sem, self._opid)
80
81 def __setstate__(self, state):
82 (self._maxsize, self._reader, self._writer,
83 self._rlock, self._wlock, self._sem, self._opid) = state
84 self._after_fork()
85
86 def _after_fork(self):
87 debug('Queue._after_fork()')
88 self._notempty = threading.Condition(threading.Lock())
89 self._buffer = collections.deque()
90 self._thread = None
91 self._jointhread = None
92 self._joincancelled = False
93 self._closed = False
94 self._close = None
95 self._send = self._writer.send
96 self._recv = self._reader.recv
97 self._poll = self._reader.poll
98
99 def put(self, obj, block=True, timeout=None):
100 assert not self._closed
101 if not self._sem.acquire(block, timeout):
102 raise Full
103
104 self._notempty.acquire()
105 try:
106 if self._thread is None:
107 self._start_thread()
108 self._buffer.append(obj)
109 self._notempty.notify()
110 finally:
111 self._notempty.release()
112
113 def get(self, block=True, timeout=None):
114 if block and timeout is None:
115 self._rlock.acquire()
116 try:
117 res = self._recv()
118 self._sem.release()
119 return res
120 finally:
121 self._rlock.release()
122
123 else:
124 if block:
125 deadline = time.time() + timeout
126 if not self._rlock.acquire(block, timeout):
127 raise Empty
128 try:
Antoine Pitroua3651132011-11-10 00:37:09 +0100129 if block:
130 timeout = deadline - time.time()
131 if timeout < 0 or not self._poll(timeout):
132 raise Empty
133 elif not self._poll():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000134 raise Empty
135 res = self._recv()
136 self._sem.release()
137 return res
138 finally:
139 self._rlock.release()
140
141 def qsize(self):
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000142 # Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000143 return self._maxsize - self._sem._semlock._get_value()
144
145 def empty(self):
146 return not self._poll()
147
148 def full(self):
149 return self._sem._semlock._is_zero()
150
151 def get_nowait(self):
152 return self.get(False)
153
154 def put_nowait(self, obj):
155 return self.put(obj, False)
156
157 def close(self):
158 self._closed = True
159 self._reader.close()
160 if self._close:
161 self._close()
162
163 def join_thread(self):
164 debug('Queue.join_thread()')
165 assert self._closed
166 if self._jointhread:
167 self._jointhread()
168
169 def cancel_join_thread(self):
170 debug('Queue.cancel_join_thread()')
171 self._joincancelled = True
172 try:
173 self._jointhread.cancel()
174 except AttributeError:
175 pass
176
177 def _start_thread(self):
178 debug('Queue._start_thread()')
179
180 # Start thread which transfers data from buffer to pipe
181 self._buffer.clear()
182 self._thread = threading.Thread(
183 target=Queue._feed,
184 args=(self._buffer, self._notempty, self._send,
185 self._wlock, self._writer.close),
186 name='QueueFeederThread'
187 )
Benjamin Peterson72753702008-08-18 18:09:21 +0000188 self._thread.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000189
190 debug('doing self._thread.start()')
191 self._thread.start()
192 debug('... done self._thread.start()')
193
194 # On process exit we will wait for data to be flushed to pipe.
195 #
196 # However, if this process created the queue then all
197 # processes which use the queue will be descendants of this
198 # process. Therefore waiting for the queue to be flushed
199 # is pointless once all the child processes have been joined.
200 created_by_this_process = (self._opid == os.getpid())
201 if not self._joincancelled and not created_by_this_process:
202 self._jointhread = Finalize(
203 self._thread, Queue._finalize_join,
204 [weakref.ref(self._thread)],
205 exitpriority=-5
206 )
207
208 # Send sentinel to the thread queue object when garbage collected
209 self._close = Finalize(
210 self, Queue._finalize_close,
211 [self._buffer, self._notempty],
212 exitpriority=10
213 )
214
215 @staticmethod
216 def _finalize_join(twr):
217 debug('joining queue thread')
218 thread = twr()
219 if thread is not None:
220 thread.join()
221 debug('... queue thread joined')
222 else:
223 debug('... queue thread already dead')
224
225 @staticmethod
226 def _finalize_close(buffer, notempty):
227 debug('telling queue thread to quit')
228 notempty.acquire()
229 try:
230 buffer.append(_sentinel)
231 notempty.notify()
232 finally:
233 notempty.release()
234
235 @staticmethod
236 def _feed(buffer, notempty, send, writelock, close):
237 debug('starting thread to feed data to pipe')
238 from .util import is_exiting
239
240 nacquire = notempty.acquire
241 nrelease = notempty.release
242 nwait = notempty.wait
243 bpopleft = buffer.popleft
244 sentinel = _sentinel
245 if sys.platform != 'win32':
246 wacquire = writelock.acquire
247 wrelease = writelock.release
248 else:
249 wacquire = None
250
251 try:
252 while 1:
253 nacquire()
254 try:
255 if not buffer:
256 nwait()
257 finally:
258 nrelease()
259 try:
260 while 1:
261 obj = bpopleft()
262 if obj is sentinel:
263 debug('feeder thread got sentinel -- exiting')
264 close()
265 return
266
267 if wacquire is None:
268 send(obj)
269 else:
270 wacquire()
271 try:
272 send(obj)
273 finally:
274 wrelease()
275 except IndexError:
276 pass
277 except Exception as e:
278 # Since this runs in a daemon thread the resources it uses
279 # may be become unusable while the process is cleaning up.
280 # We ignore errors which happen after the process has
281 # started to cleanup.
282 try:
283 if is_exiting():
284 info('error in queue thread: %s', e)
285 else:
286 import traceback
287 traceback.print_exc()
288 except Exception:
289 pass
290
291_sentinel = object()
292
293#
294# A queue type which also supports join() and task_done() methods
295#
296# Note that if you do not call task_done() for each finished task then
297# eventually the counter's semaphore may overflow causing Bad Things
298# to happen.
299#
300
301class JoinableQueue(Queue):
302
303 def __init__(self, maxsize=0):
304 Queue.__init__(self, maxsize)
305 self._unfinished_tasks = Semaphore(0)
306 self._cond = Condition()
307
308 def __getstate__(self):
309 return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks)
310
311 def __setstate__(self, state):
312 Queue.__setstate__(self, state[:-2])
313 self._cond, self._unfinished_tasks = state[-2:]
314
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000315 def put(self, obj, block=True, timeout=None):
316 assert not self._closed
317 if not self._sem.acquire(block, timeout):
318 raise Full
319
320 self._notempty.acquire()
321 self._cond.acquire()
322 try:
323 if self._thread is None:
324 self._start_thread()
325 self._buffer.append(obj)
326 self._unfinished_tasks.release()
327 self._notempty.notify()
328 finally:
329 self._cond.release()
330 self._notempty.release()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000331
332 def task_done(self):
333 self._cond.acquire()
334 try:
335 if not self._unfinished_tasks.acquire(False):
336 raise ValueError('task_done() called too many times')
337 if self._unfinished_tasks._semlock._is_zero():
338 self._cond.notify_all()
339 finally:
340 self._cond.release()
341
342 def join(self):
343 self._cond.acquire()
344 try:
345 if not self._unfinished_tasks._semlock._is_zero():
346 self._cond.wait()
347 finally:
348 self._cond.release()
349
350#
351# Simplified Queue type -- really just a locked pipe
352#
353
354class SimpleQueue(object):
355
356 def __init__(self):
357 self._reader, self._writer = Pipe(duplex=False)
358 self._rlock = Lock()
359 if sys.platform == 'win32':
360 self._wlock = None
361 else:
362 self._wlock = Lock()
363 self._make_methods()
364
365 def empty(self):
366 return not self._reader.poll()
367
368 def __getstate__(self):
369 assert_spawning(self)
370 return (self._reader, self._writer, self._rlock, self._wlock)
371
372 def __setstate__(self, state):
373 (self._reader, self._writer, self._rlock, self._wlock) = state
374 self._make_methods()
375
376 def _make_methods(self):
377 recv = self._reader.recv
378 racquire, rrelease = self._rlock.acquire, self._rlock.release
379 def get():
380 racquire()
381 try:
382 return recv()
383 finally:
384 rrelease()
385 self.get = get
386
387 if self._wlock is None:
388 # writes to a message oriented win32 pipe are atomic
389 self.put = self._writer.send
390 else:
391 send = self._writer.send
392 wacquire, wrelease = self._wlock.acquire, self._wlock.release
393 def put(obj):
394 wacquire()
395 try:
396 return send(obj)
397 finally:
398 wrelease()
399 self.put = put