blob: 7a6d014901463e6fd578d30b9b5e24d115cf1783 [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module providing the `Pool` class for managing a process pool
3#
4# multiprocessing/pool.py
5#
R. David Murray3fc969a2010-12-14 01:38:16 +00006# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +01007# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +00008#
9
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010010__all__ = ['Pool', 'ThreadPool']
Benjamin Petersone711caf2008-06-11 16:44:04 +000011
12#
13# Imports
14#
15
16import threading
17import queue
18import itertools
19import collections
Charles-François Natali37cfb0a2013-06-28 19:25:45 +020020import os
Benjamin Petersone711caf2008-06-11 16:44:04 +000021import time
Richard Oudkerk85757832013-05-06 11:38:25 +010022import traceback
Benjamin Petersone711caf2008-06-11 16:44:04 +000023
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010024# If threading is available then ThreadPool should be provided. Therefore
25# we avoid top-level imports which are liable to fail on some systems.
26from . import util
Victor Stinner7fa767e2014-03-20 09:16:38 +010027from . import get_context, TimeoutError
Benjamin Petersone711caf2008-06-11 16:44:04 +000028
29#
30# Constants representing the state of a pool
31#
32
33RUN = 0
34CLOSE = 1
35TERMINATE = 2
36
37#
38# Miscellaneous
39#
40
41job_counter = itertools.count()
42
43def mapstar(args):
44 return list(map(*args))
45
Antoine Pitroude911b22011-12-21 11:03:24 +010046def starmapstar(args):
47 return list(itertools.starmap(args[0], args[1]))
48
Benjamin Petersone711caf2008-06-11 16:44:04 +000049#
Richard Oudkerk85757832013-05-06 11:38:25 +010050# Hack to embed stringification of remote traceback in local traceback
51#
52
53class RemoteTraceback(Exception):
54 def __init__(self, tb):
55 self.tb = tb
56 def __str__(self):
57 return self.tb
58
59class ExceptionWithTraceback:
60 def __init__(self, exc, tb):
61 tb = traceback.format_exception(type(exc), exc, tb)
62 tb = ''.join(tb)
63 self.exc = exc
64 self.tb = '\n"""\n%s"""' % tb
65 def __reduce__(self):
66 return rebuild_exc, (self.exc, self.tb)
67
68def rebuild_exc(exc, tb):
69 exc.__cause__ = RemoteTraceback(tb)
70 return exc
71
72#
Benjamin Petersone711caf2008-06-11 16:44:04 +000073# Code run by worker processes
74#
75
Ask Solem2afcbf22010-11-09 20:55:52 +000076class MaybeEncodingError(Exception):
77 """Wraps possible unpickleable errors, so they can be
78 safely sent through the socket."""
79
80 def __init__(self, exc, value):
81 self.exc = repr(exc)
82 self.value = repr(value)
83 super(MaybeEncodingError, self).__init__(self.exc, self.value)
84
85 def __str__(self):
86 return "Error sending result: '%s'. Reason: '%s'" % (self.value,
87 self.exc)
88
89 def __repr__(self):
Serhiy Storchaka465e60e2014-07-25 23:36:00 +030090 return "<%s: %s>" % (self.__class__.__name__, self)
Ask Solem2afcbf22010-11-09 20:55:52 +000091
92
Richard Oudkerk80a5be12014-03-23 12:30:54 +000093def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None,
94 wrap_exception=False):
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -050095 if (maxtasks is not None) and not (isinstance(maxtasks, int)
96 and maxtasks >= 1):
97 raise AssertionError("Maxtasks {!r} is not valid".format(maxtasks))
Benjamin Petersone711caf2008-06-11 16:44:04 +000098 put = outqueue.put
99 get = inqueue.get
100 if hasattr(inqueue, '_writer'):
101 inqueue._writer.close()
102 outqueue._reader.close()
103
104 if initializer is not None:
105 initializer(*initargs)
106
Jesse Noller1f0b6582010-01-27 03:36:01 +0000107 completed = 0
108 while maxtasks is None or (maxtasks and completed < maxtasks):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000109 try:
110 task = get()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200111 except (EOFError, OSError):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100112 util.debug('worker got EOFError or OSError -- exiting')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000113 break
114
115 if task is None:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100116 util.debug('worker got sentinel -- exiting')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000117 break
118
119 job, i, func, args, kwds = task
120 try:
121 result = (True, func(*args, **kwds))
122 except Exception as e:
Xiang Zhang794623b2017-03-29 11:58:54 +0800123 if wrap_exception and func is not _helper_reraises_exception:
Richard Oudkerk80a5be12014-03-23 12:30:54 +0000124 e = ExceptionWithTraceback(e, e.__traceback__)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000125 result = (False, e)
Ask Solem2afcbf22010-11-09 20:55:52 +0000126 try:
127 put((job, i, result))
128 except Exception as e:
129 wrapped = MaybeEncodingError(e, result[1])
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100130 util.debug("Possible encoding error while sending result: %s" % (
Ask Solem2afcbf22010-11-09 20:55:52 +0000131 wrapped))
132 put((job, i, (False, wrapped)))
Antoine Pitrou89889452017-03-24 13:52:11 +0100133
134 task = job = result = func = args = kwds = None
Jesse Noller1f0b6582010-01-27 03:36:01 +0000135 completed += 1
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100136 util.debug('worker exiting after %d tasks' % completed)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000137
Xiang Zhang794623b2017-03-29 11:58:54 +0800138def _helper_reraises_exception(ex):
139 'Pickle-able helper function for use by _guarded_task_generation.'
140 raise ex
141
Benjamin Petersone711caf2008-06-11 16:44:04 +0000142#
143# Class representing a process pool
144#
145
146class Pool(object):
147 '''
Georg Brandl92905032008-11-22 08:51:39 +0000148 Class which supports an async version of applying functions to arguments.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000149 '''
Richard Oudkerk80a5be12014-03-23 12:30:54 +0000150 _wrap_exception = True
151
tzickel97bfe8d2018-10-03 00:01:23 +0300152 @staticmethod
153 def Process(ctx, *args, **kwds):
154 return ctx.Process(*args, **kwds)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000155
Jesse Noller1f0b6582010-01-27 03:36:01 +0000156 def __init__(self, processes=None, initializer=None, initargs=(),
Richard Oudkerkb1694cf2013-10-16 16:41:56 +0100157 maxtasksperchild=None, context=None):
158 self._ctx = context or get_context()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000159 self._setup_queues()
Antoine Pitrouab745042018-01-18 10:38:03 +0100160 self._taskqueue = queue.SimpleQueue()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000161 self._cache = {}
162 self._state = RUN
Jesse Noller1f0b6582010-01-27 03:36:01 +0000163 self._maxtasksperchild = maxtasksperchild
164 self._initializer = initializer
165 self._initargs = initargs
Benjamin Petersone711caf2008-06-11 16:44:04 +0000166
167 if processes is None:
Charles-François Natali37cfb0a2013-06-28 19:25:45 +0200168 processes = os.cpu_count() or 1
Victor Stinner2fae27b2011-06-20 17:53:35 +0200169 if processes < 1:
170 raise ValueError("Number of processes must be at least 1")
Benjamin Petersone711caf2008-06-11 16:44:04 +0000171
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200172 if initializer is not None and not callable(initializer):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000173 raise TypeError('initializer must be a callable')
174
Jesse Noller1f0b6582010-01-27 03:36:01 +0000175 self._processes = processes
Benjamin Petersone711caf2008-06-11 16:44:04 +0000176 self._pool = []
Julien Palard5d236ca2018-11-04 23:40:32 +0100177 try:
178 self._repopulate_pool()
179 except Exception:
180 for p in self._pool:
181 if p.exitcode is None:
182 p.terminate()
183 for p in self._pool:
184 p.join()
185 raise
Jesse Noller1f0b6582010-01-27 03:36:01 +0000186
187 self._worker_handler = threading.Thread(
188 target=Pool._handle_workers,
tzickel97bfe8d2018-10-03 00:01:23 +0300189 args=(self._cache, self._taskqueue, self._ctx, self.Process,
190 self._processes, self._pool, self._inqueue, self._outqueue,
191 self._initializer, self._initargs, self._maxtasksperchild,
192 self._wrap_exception)
Jesse Noller1f0b6582010-01-27 03:36:01 +0000193 )
194 self._worker_handler.daemon = True
195 self._worker_handler._state = RUN
196 self._worker_handler.start()
197
Benjamin Petersone711caf2008-06-11 16:44:04 +0000198 self._task_handler = threading.Thread(
199 target=Pool._handle_tasks,
Richard Oudkerke90cedb2013-10-28 23:11:58 +0000200 args=(self._taskqueue, self._quick_put, self._outqueue,
201 self._pool, self._cache)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000202 )
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000203 self._task_handler.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000204 self._task_handler._state = RUN
205 self._task_handler.start()
206
207 self._result_handler = threading.Thread(
208 target=Pool._handle_results,
209 args=(self._outqueue, self._quick_get, self._cache)
210 )
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000211 self._result_handler.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000212 self._result_handler._state = RUN
213 self._result_handler.start()
214
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100215 self._terminate = util.Finalize(
Benjamin Petersone711caf2008-06-11 16:44:04 +0000216 self, self._terminate_pool,
217 args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
Jesse Noller1f0b6582010-01-27 03:36:01 +0000218 self._worker_handler, self._task_handler,
219 self._result_handler, self._cache),
Benjamin Petersone711caf2008-06-11 16:44:04 +0000220 exitpriority=15
221 )
222
tzickel97bfe8d2018-10-03 00:01:23 +0300223 @staticmethod
224 def _join_exited_workers(pool):
Jesse Noller1f0b6582010-01-27 03:36:01 +0000225 """Cleanup after any worker processes which have exited due to reaching
226 their specified lifetime. Returns True if any workers were cleaned up.
227 """
228 cleaned = False
tzickel97bfe8d2018-10-03 00:01:23 +0300229 for i in reversed(range(len(pool))):
230 worker = pool[i]
Jesse Noller1f0b6582010-01-27 03:36:01 +0000231 if worker.exitcode is not None:
232 # worker exited
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100233 util.debug('cleaning up worker %d' % i)
Jesse Noller1f0b6582010-01-27 03:36:01 +0000234 worker.join()
235 cleaned = True
tzickel97bfe8d2018-10-03 00:01:23 +0300236 del pool[i]
Jesse Noller1f0b6582010-01-27 03:36:01 +0000237 return cleaned
238
239 def _repopulate_pool(self):
tzickel97bfe8d2018-10-03 00:01:23 +0300240 return self._repopulate_pool_static(self._ctx, self.Process,
241 self._processes,
242 self._pool, self._inqueue,
243 self._outqueue, self._initializer,
244 self._initargs,
245 self._maxtasksperchild,
246 self._wrap_exception)
247
248 @staticmethod
249 def _repopulate_pool_static(ctx, Process, processes, pool, inqueue,
250 outqueue, initializer, initargs,
251 maxtasksperchild, wrap_exception):
Jesse Noller1f0b6582010-01-27 03:36:01 +0000252 """Bring the number of pool processes up to the specified number,
253 for use after reaping workers which have exited.
254 """
tzickel97bfe8d2018-10-03 00:01:23 +0300255 for i in range(processes - len(pool)):
256 w = Process(ctx, target=worker,
257 args=(inqueue, outqueue,
258 initializer,
259 initargs, maxtasksperchild,
260 wrap_exception)
261 )
Jesse Noller1f0b6582010-01-27 03:36:01 +0000262 w.name = w.name.replace('Process', 'PoolWorker')
263 w.daemon = True
264 w.start()
Julien Palard5d236ca2018-11-04 23:40:32 +0100265 pool.append(w)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100266 util.debug('added worker')
Jesse Noller1f0b6582010-01-27 03:36:01 +0000267
tzickel97bfe8d2018-10-03 00:01:23 +0300268 @staticmethod
269 def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue,
270 initializer, initargs, maxtasksperchild,
271 wrap_exception):
Jesse Noller1f0b6582010-01-27 03:36:01 +0000272 """Clean up any exited workers and start replacements for them.
273 """
tzickel97bfe8d2018-10-03 00:01:23 +0300274 if Pool._join_exited_workers(pool):
275 Pool._repopulate_pool_static(ctx, Process, processes, pool,
276 inqueue, outqueue, initializer,
277 initargs, maxtasksperchild,
278 wrap_exception)
Jesse Noller1f0b6582010-01-27 03:36:01 +0000279
Benjamin Petersone711caf2008-06-11 16:44:04 +0000280 def _setup_queues(self):
Richard Oudkerkb1694cf2013-10-16 16:41:56 +0100281 self._inqueue = self._ctx.SimpleQueue()
282 self._outqueue = self._ctx.SimpleQueue()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000283 self._quick_put = self._inqueue._writer.send
284 self._quick_get = self._outqueue._reader.recv
285
286 def apply(self, func, args=(), kwds={}):
287 '''
Georg Brandl92905032008-11-22 08:51:39 +0000288 Equivalent of `func(*args, **kwds)`.
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500289 Pool must be running.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000290 '''
Benjamin Petersone711caf2008-06-11 16:44:04 +0000291 return self.apply_async(func, args, kwds).get()
292
293 def map(self, func, iterable, chunksize=None):
294 '''
Georg Brandl92905032008-11-22 08:51:39 +0000295 Apply `func` to each element in `iterable`, collecting the results
296 in a list that is returned.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000297 '''
Antoine Pitroude911b22011-12-21 11:03:24 +0100298 return self._map_async(func, iterable, mapstar, chunksize).get()
299
300 def starmap(self, func, iterable, chunksize=None):
301 '''
302 Like `map()` method but the elements of the `iterable` are expected to
303 be iterables as well and will be unpacked as arguments. Hence
304 `func` and (a, b) becomes func(a, b).
305 '''
Antoine Pitroude911b22011-12-21 11:03:24 +0100306 return self._map_async(func, iterable, starmapstar, chunksize).get()
307
308 def starmap_async(self, func, iterable, chunksize=None, callback=None,
309 error_callback=None):
310 '''
311 Asynchronous version of `starmap()` method.
312 '''
Antoine Pitroude911b22011-12-21 11:03:24 +0100313 return self._map_async(func, iterable, starmapstar, chunksize,
314 callback, error_callback)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000315
Xiang Zhang794623b2017-03-29 11:58:54 +0800316 def _guarded_task_generation(self, result_job, func, iterable):
317 '''Provides a generator of tasks for imap and imap_unordered with
318 appropriate handling for iterables which throw exceptions during
319 iteration.'''
320 try:
321 i = -1
322 for i, x in enumerate(iterable):
323 yield (result_job, i, func, (x,), {})
324 except Exception as e:
325 yield (result_job, i+1, _helper_reraises_exception, (e,), {})
326
Benjamin Petersone711caf2008-06-11 16:44:04 +0000327 def imap(self, func, iterable, chunksize=1):
328 '''
Georg Brandl92905032008-11-22 08:51:39 +0000329 Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000330 '''
Benjamin Peterson3095f472012-09-25 12:45:42 -0400331 if self._state != RUN:
332 raise ValueError("Pool not running")
Benjamin Petersone711caf2008-06-11 16:44:04 +0000333 if chunksize == 1:
334 result = IMapIterator(self._cache)
Xiang Zhang794623b2017-03-29 11:58:54 +0800335 self._taskqueue.put(
336 (
337 self._guarded_task_generation(result._job, func, iterable),
338 result._set_length
339 ))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000340 return result
341 else:
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500342 if chunksize < 1:
343 raise ValueError(
344 "Chunksize must be 1+, not {0:n}".format(
345 chunksize))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000346 task_batches = Pool._get_tasks(func, iterable, chunksize)
347 result = IMapIterator(self._cache)
Xiang Zhang794623b2017-03-29 11:58:54 +0800348 self._taskqueue.put(
349 (
350 self._guarded_task_generation(result._job,
351 mapstar,
352 task_batches),
353 result._set_length
354 ))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000355 return (item for chunk in result for item in chunk)
356
357 def imap_unordered(self, func, iterable, chunksize=1):
358 '''
Georg Brandl92905032008-11-22 08:51:39 +0000359 Like `imap()` method but ordering of results is arbitrary.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000360 '''
Benjamin Peterson3095f472012-09-25 12:45:42 -0400361 if self._state != RUN:
362 raise ValueError("Pool not running")
Benjamin Petersone711caf2008-06-11 16:44:04 +0000363 if chunksize == 1:
364 result = IMapUnorderedIterator(self._cache)
Xiang Zhang794623b2017-03-29 11:58:54 +0800365 self._taskqueue.put(
366 (
367 self._guarded_task_generation(result._job, func, iterable),
368 result._set_length
369 ))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000370 return result
371 else:
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500372 if chunksize < 1:
373 raise ValueError(
374 "Chunksize must be 1+, not {0!r}".format(chunksize))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000375 task_batches = Pool._get_tasks(func, iterable, chunksize)
376 result = IMapUnorderedIterator(self._cache)
Xiang Zhang794623b2017-03-29 11:58:54 +0800377 self._taskqueue.put(
378 (
379 self._guarded_task_generation(result._job,
380 mapstar,
381 task_batches),
382 result._set_length
383 ))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000384 return (item for chunk in result for item in chunk)
385
Ask Solem2afcbf22010-11-09 20:55:52 +0000386 def apply_async(self, func, args=(), kwds={}, callback=None,
387 error_callback=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000388 '''
Georg Brandl92905032008-11-22 08:51:39 +0000389 Asynchronous version of `apply()` method.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000390 '''
Benjamin Peterson3095f472012-09-25 12:45:42 -0400391 if self._state != RUN:
392 raise ValueError("Pool not running")
Ask Solem2afcbf22010-11-09 20:55:52 +0000393 result = ApplyResult(self._cache, callback, error_callback)
Xiang Zhang794623b2017-03-29 11:58:54 +0800394 self._taskqueue.put(([(result._job, 0, func, args, kwds)], None))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000395 return result
396
Ask Solem2afcbf22010-11-09 20:55:52 +0000397 def map_async(self, func, iterable, chunksize=None, callback=None,
398 error_callback=None):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000399 '''
Georg Brandl92905032008-11-22 08:51:39 +0000400 Asynchronous version of `map()` method.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000401 '''
Hynek Schlawack254af262012-10-27 12:53:02 +0200402 return self._map_async(func, iterable, mapstar, chunksize, callback,
403 error_callback)
Antoine Pitroude911b22011-12-21 11:03:24 +0100404
405 def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
406 error_callback=None):
407 '''
408 Helper function to implement map, starmap and their async counterparts.
409 '''
Benjamin Peterson3095f472012-09-25 12:45:42 -0400410 if self._state != RUN:
411 raise ValueError("Pool not running")
Benjamin Petersone711caf2008-06-11 16:44:04 +0000412 if not hasattr(iterable, '__len__'):
413 iterable = list(iterable)
414
415 if chunksize is None:
416 chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
417 if extra:
418 chunksize += 1
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000419 if len(iterable) == 0:
420 chunksize = 0
Benjamin Petersone711caf2008-06-11 16:44:04 +0000421
422 task_batches = Pool._get_tasks(func, iterable, chunksize)
Ask Solem2afcbf22010-11-09 20:55:52 +0000423 result = MapResult(self._cache, chunksize, len(iterable), callback,
424 error_callback=error_callback)
Xiang Zhang794623b2017-03-29 11:58:54 +0800425 self._taskqueue.put(
426 (
427 self._guarded_task_generation(result._job,
428 mapper,
429 task_batches),
430 None
431 )
432 )
Benjamin Petersone711caf2008-06-11 16:44:04 +0000433 return result
434
435 @staticmethod
tzickel97bfe8d2018-10-03 00:01:23 +0300436 def _handle_workers(cache, taskqueue, ctx, Process, processes, pool,
437 inqueue, outqueue, initializer, initargs,
438 maxtasksperchild, wrap_exception):
Charles-François Natalif8859e12011-10-24 18:45:29 +0200439 thread = threading.current_thread()
440
441 # Keep maintaining workers until the cache gets drained, unless the pool
442 # is terminated.
tzickel97bfe8d2018-10-03 00:01:23 +0300443 while thread._state == RUN or (cache and thread._state != TERMINATE):
444 Pool._maintain_pool(ctx, Process, processes, pool, inqueue,
445 outqueue, initializer, initargs,
446 maxtasksperchild, wrap_exception)
Jesse Noller1f0b6582010-01-27 03:36:01 +0000447 time.sleep(0.1)
Antoine Pitrou81dee6b2011-04-11 00:18:59 +0200448 # send sentinel to stop workers
tzickel97bfe8d2018-10-03 00:01:23 +0300449 taskqueue.put(None)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100450 util.debug('worker handler exiting')
Jesse Noller1f0b6582010-01-27 03:36:01 +0000451
452 @staticmethod
Richard Oudkerke90cedb2013-10-28 23:11:58 +0000453 def _handle_tasks(taskqueue, put, outqueue, pool, cache):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000454 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000455
456 for taskseq, set_length in iter(taskqueue.get, None):
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200457 task = None
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200458 try:
Xiang Zhang794623b2017-03-29 11:58:54 +0800459 # iterating taskseq cannot fail
460 for task in taskseq:
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200461 if thread._state:
462 util.debug('task handler found thread._state != RUN')
463 break
Richard Oudkerke90cedb2013-10-28 23:11:58 +0000464 try:
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200465 put(task)
466 except Exception as e:
Xiang Zhang794623b2017-03-29 11:58:54 +0800467 job, idx = task[:2]
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200468 try:
Xiang Zhang794623b2017-03-29 11:58:54 +0800469 cache[job]._set(idx, (False, e))
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200470 except KeyError:
471 pass
472 else:
473 if set_length:
474 util.debug('doing set_length()')
Xiang Zhang794623b2017-03-29 11:58:54 +0800475 idx = task[1] if task else -1
476 set_length(idx + 1)
Serhiy Storchaka79fbeee2015-03-13 08:25:26 +0200477 continue
478 break
Antoine Pitrou89889452017-03-24 13:52:11 +0100479 finally:
480 task = taskseq = job = None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000481 else:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100482 util.debug('task handler got sentinel')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000483
Benjamin Petersone711caf2008-06-11 16:44:04 +0000484 try:
485 # tell result handler to finish when cache is empty
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100486 util.debug('task handler sending sentinel to result handler')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000487 outqueue.put(None)
488
489 # tell workers there is no more work
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100490 util.debug('task handler sending sentinel to workers')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000491 for p in pool:
492 put(None)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200493 except OSError:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100494 util.debug('task handler got OSError when sending sentinels')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000495
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100496 util.debug('task handler exiting')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000497
498 @staticmethod
499 def _handle_results(outqueue, get, cache):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000500 thread = threading.current_thread()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000501
502 while 1:
503 try:
504 task = get()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200505 except (OSError, EOFError):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100506 util.debug('result handler got EOFError/OSError -- exiting')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000507 return
508
509 if thread._state:
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500510 assert thread._state == TERMINATE, "Thread not in TERMINATE"
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100511 util.debug('result handler found thread._state=TERMINATE')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000512 break
513
514 if task is None:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100515 util.debug('result handler got sentinel')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000516 break
517
518 job, i, obj = task
519 try:
520 cache[job]._set(i, obj)
521 except KeyError:
522 pass
Antoine Pitrou89889452017-03-24 13:52:11 +0100523 task = job = obj = None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000524
525 while cache and thread._state != TERMINATE:
526 try:
527 task = get()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200528 except (OSError, EOFError):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100529 util.debug('result handler got EOFError/OSError -- exiting')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000530 return
531
532 if task is None:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100533 util.debug('result handler ignoring extra sentinel')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000534 continue
535 job, i, obj = task
536 try:
537 cache[job]._set(i, obj)
538 except KeyError:
539 pass
Antoine Pitrou89889452017-03-24 13:52:11 +0100540 task = job = obj = None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000541
542 if hasattr(outqueue, '_reader'):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100543 util.debug('ensuring that outqueue is not full')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000544 # If we don't make room available in outqueue then
545 # attempts to add the sentinel (None) to outqueue may
546 # block. There is guaranteed to be no more than 2 sentinels.
547 try:
548 for i in range(10):
549 if not outqueue._reader.poll():
550 break
551 get()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200552 except (OSError, EOFError):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000553 pass
554
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100555 util.debug('result handler exiting: len(cache)=%s, thread._state=%s',
Benjamin Petersone711caf2008-06-11 16:44:04 +0000556 len(cache), thread._state)
557
558 @staticmethod
559 def _get_tasks(func, it, size):
560 it = iter(it)
561 while 1:
562 x = tuple(itertools.islice(it, size))
563 if not x:
564 return
565 yield (func, x)
566
567 def __reduce__(self):
568 raise NotImplementedError(
569 'pool objects cannot be passed between processes or pickled'
570 )
571
572 def close(self):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100573 util.debug('closing pool')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000574 if self._state == RUN:
575 self._state = CLOSE
Jesse Noller1f0b6582010-01-27 03:36:01 +0000576 self._worker_handler._state = CLOSE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000577
578 def terminate(self):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100579 util.debug('terminating pool')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000580 self._state = TERMINATE
Jesse Noller1f0b6582010-01-27 03:36:01 +0000581 self._worker_handler._state = TERMINATE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000582 self._terminate()
583
584 def join(self):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100585 util.debug('joining pool')
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500586 if self._state == RUN:
587 raise ValueError("Pool is still running")
588 elif self._state not in (CLOSE, TERMINATE):
589 raise ValueError("In unknown state")
Jesse Noller1f0b6582010-01-27 03:36:01 +0000590 self._worker_handler.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000591 self._task_handler.join()
592 self._result_handler.join()
593 for p in self._pool:
594 p.join()
595
596 @staticmethod
597 def _help_stuff_finish(inqueue, task_handler, size):
598 # task_handler may be blocked trying to put items on inqueue
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100599 util.debug('removing tasks from inqueue until task handler finished')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000600 inqueue._rlock.acquire()
Benjamin Peterson672b8032008-06-11 19:14:14 +0000601 while task_handler.is_alive() and inqueue._reader.poll():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000602 inqueue._reader.recv()
603 time.sleep(0)
604
605 @classmethod
606 def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool,
Jesse Noller1f0b6582010-01-27 03:36:01 +0000607 worker_handler, task_handler, result_handler, cache):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000608 # this is guaranteed to only be called once
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100609 util.debug('finalizing pool')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000610
Jesse Noller1f0b6582010-01-27 03:36:01 +0000611 worker_handler._state = TERMINATE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000612 task_handler._state = TERMINATE
Benjamin Petersone711caf2008-06-11 16:44:04 +0000613
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100614 util.debug('helping task handler/workers to finish')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000615 cls._help_stuff_finish(inqueue, task_handler, len(pool))
616
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500617 if (not result_handler.is_alive()) and (len(cache) != 0):
618 raise AssertionError(
619 "Cannot have cache with result_hander not alive")
Benjamin Petersone711caf2008-06-11 16:44:04 +0000620
621 result_handler._state = TERMINATE
622 outqueue.put(None) # sentinel
623
Antoine Pitrou81dee6b2011-04-11 00:18:59 +0200624 # We must wait for the worker handler to exit before terminating
625 # workers because we don't want workers to be restarted behind our back.
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100626 util.debug('joining worker handler')
Richard Oudkerkf29ec4b2012-06-18 15:54:57 +0100627 if threading.current_thread() is not worker_handler:
628 worker_handler.join()
Antoine Pitrou81dee6b2011-04-11 00:18:59 +0200629
Jesse Noller1f0b6582010-01-27 03:36:01 +0000630 # Terminate workers which haven't already finished.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000631 if pool and hasattr(pool[0], 'terminate'):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100632 util.debug('terminating workers')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000633 for p in pool:
Jesse Noller1f0b6582010-01-27 03:36:01 +0000634 if p.exitcode is None:
635 p.terminate()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000636
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100637 util.debug('joining task handler')
Richard Oudkerkf29ec4b2012-06-18 15:54:57 +0100638 if threading.current_thread() is not task_handler:
639 task_handler.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000640
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100641 util.debug('joining result handler')
Richard Oudkerkf29ec4b2012-06-18 15:54:57 +0100642 if threading.current_thread() is not result_handler:
643 result_handler.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000644
645 if pool and hasattr(pool[0], 'terminate'):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100646 util.debug('joining pool workers')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000647 for p in pool:
Florent Xicluna998171f2010-03-08 13:32:17 +0000648 if p.is_alive():
Jesse Noller1f0b6582010-01-27 03:36:01 +0000649 # worker has not yet exited
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100650 util.debug('cleaning up worker %d' % p.pid)
Florent Xicluna998171f2010-03-08 13:32:17 +0000651 p.join()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000652
Richard Oudkerkd69cfe82012-06-18 17:47:52 +0100653 def __enter__(self):
654 return self
655
656 def __exit__(self, exc_type, exc_val, exc_tb):
657 self.terminate()
658
Benjamin Petersone711caf2008-06-11 16:44:04 +0000659#
660# Class whose instances are returned by `Pool.apply_async()`
661#
662
663class ApplyResult(object):
664
Ask Solem2afcbf22010-11-09 20:55:52 +0000665 def __init__(self, cache, callback, error_callback):
Richard Oudkerk692130a2012-05-25 13:26:53 +0100666 self._event = threading.Event()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000667 self._job = next(job_counter)
668 self._cache = cache
Benjamin Petersone711caf2008-06-11 16:44:04 +0000669 self._callback = callback
Ask Solem2afcbf22010-11-09 20:55:52 +0000670 self._error_callback = error_callback
Benjamin Petersone711caf2008-06-11 16:44:04 +0000671 cache[self._job] = self
672
673 def ready(self):
Richard Oudkerk692130a2012-05-25 13:26:53 +0100674 return self._event.is_set()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000675
676 def successful(self):
Allen W. Smith, Ph.Dbd73e722017-08-29 17:52:18 -0500677 if not self.ready():
678 raise ValueError("{0!r} not ready".format(self))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000679 return self._success
680
681 def wait(self, timeout=None):
Richard Oudkerk692130a2012-05-25 13:26:53 +0100682 self._event.wait(timeout)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000683
684 def get(self, timeout=None):
685 self.wait(timeout)
Richard Oudkerk692130a2012-05-25 13:26:53 +0100686 if not self.ready():
Benjamin Petersone711caf2008-06-11 16:44:04 +0000687 raise TimeoutError
688 if self._success:
689 return self._value
690 else:
691 raise self._value
692
693 def _set(self, i, obj):
694 self._success, self._value = obj
695 if self._callback and self._success:
696 self._callback(self._value)
Ask Solem2afcbf22010-11-09 20:55:52 +0000697 if self._error_callback and not self._success:
698 self._error_callback(self._value)
Richard Oudkerk692130a2012-05-25 13:26:53 +0100699 self._event.set()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000700 del self._cache[self._job]
701
Richard Oudkerkdef51ca2013-05-06 12:10:04 +0100702AsyncResult = ApplyResult # create alias -- see #17805
703
Benjamin Petersone711caf2008-06-11 16:44:04 +0000704#
705# Class whose instances are returned by `Pool.map_async()`
706#
707
708class MapResult(ApplyResult):
709
Ask Solem2afcbf22010-11-09 20:55:52 +0000710 def __init__(self, cache, chunksize, length, callback, error_callback):
711 ApplyResult.__init__(self, cache, callback,
712 error_callback=error_callback)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000713 self._success = True
714 self._value = [None] * length
715 self._chunksize = chunksize
716 if chunksize <= 0:
717 self._number_left = 0
Richard Oudkerk692130a2012-05-25 13:26:53 +0100718 self._event.set()
Richard Oudkerke41682b2012-06-06 19:04:57 +0100719 del cache[self._job]
Benjamin Petersone711caf2008-06-11 16:44:04 +0000720 else:
721 self._number_left = length//chunksize + bool(length % chunksize)
722
723 def _set(self, i, success_result):
Charles-François Natali78f55ff2016-02-10 22:58:18 +0000724 self._number_left -= 1
Benjamin Petersone711caf2008-06-11 16:44:04 +0000725 success, result = success_result
Charles-François Natali78f55ff2016-02-10 22:58:18 +0000726 if success and self._success:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000727 self._value[i*self._chunksize:(i+1)*self._chunksize] = result
Benjamin Petersone711caf2008-06-11 16:44:04 +0000728 if self._number_left == 0:
729 if self._callback:
730 self._callback(self._value)
731 del self._cache[self._job]
Richard Oudkerk692130a2012-05-25 13:26:53 +0100732 self._event.set()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000733 else:
Charles-François Natali78f55ff2016-02-10 22:58:18 +0000734 if not success and self._success:
735 # only store first exception
736 self._success = False
737 self._value = result
738 if self._number_left == 0:
739 # only consider the result ready once all jobs are done
740 if self._error_callback:
741 self._error_callback(self._value)
742 del self._cache[self._job]
743 self._event.set()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000744
745#
746# Class whose instances are returned by `Pool.imap()`
747#
748
749class IMapIterator(object):
750
751 def __init__(self, cache):
752 self._cond = threading.Condition(threading.Lock())
753 self._job = next(job_counter)
754 self._cache = cache
755 self._items = collections.deque()
756 self._index = 0
757 self._length = None
758 self._unsorted = {}
759 cache[self._job] = self
760
761 def __iter__(self):
762 return self
763
764 def next(self, timeout=None):
Charles-François Natalia924fc72014-05-25 14:12:12 +0100765 with self._cond:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000766 try:
767 item = self._items.popleft()
768 except IndexError:
769 if self._index == self._length:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300770 raise StopIteration from None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000771 self._cond.wait(timeout)
772 try:
773 item = self._items.popleft()
774 except IndexError:
775 if self._index == self._length:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300776 raise StopIteration from None
777 raise TimeoutError from None
Benjamin Petersone711caf2008-06-11 16:44:04 +0000778
779 success, value = item
780 if success:
781 return value
782 raise value
783
784 __next__ = next # XXX
785
786 def _set(self, i, obj):
Charles-François Natalia924fc72014-05-25 14:12:12 +0100787 with self._cond:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000788 if self._index == i:
789 self._items.append(obj)
790 self._index += 1
791 while self._index in self._unsorted:
792 obj = self._unsorted.pop(self._index)
793 self._items.append(obj)
794 self._index += 1
795 self._cond.notify()
796 else:
797 self._unsorted[i] = obj
798
799 if self._index == self._length:
800 del self._cache[self._job]
Benjamin Petersone711caf2008-06-11 16:44:04 +0000801
802 def _set_length(self, length):
Charles-François Natalia924fc72014-05-25 14:12:12 +0100803 with self._cond:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000804 self._length = length
805 if self._index == self._length:
806 self._cond.notify()
807 del self._cache[self._job]
Benjamin Petersone711caf2008-06-11 16:44:04 +0000808
809#
810# Class whose instances are returned by `Pool.imap_unordered()`
811#
812
813class IMapUnorderedIterator(IMapIterator):
814
815 def _set(self, i, obj):
Charles-François Natalia924fc72014-05-25 14:12:12 +0100816 with self._cond:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000817 self._items.append(obj)
818 self._index += 1
819 self._cond.notify()
820 if self._index == self._length:
821 del self._cache[self._job]
Benjamin Petersone711caf2008-06-11 16:44:04 +0000822
823#
824#
825#
826
827class ThreadPool(Pool):
Richard Oudkerk80a5be12014-03-23 12:30:54 +0000828 _wrap_exception = False
Benjamin Petersone711caf2008-06-11 16:44:04 +0000829
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100830 @staticmethod
tzickel97bfe8d2018-10-03 00:01:23 +0300831 def Process(ctx, *args, **kwds):
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100832 from .dummy import Process
833 return Process(*args, **kwds)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000834
835 def __init__(self, processes=None, initializer=None, initargs=()):
836 Pool.__init__(self, processes, initializer, initargs)
837
838 def _setup_queues(self):
Antoine Pitrouab745042018-01-18 10:38:03 +0100839 self._inqueue = queue.SimpleQueue()
840 self._outqueue = queue.SimpleQueue()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000841 self._quick_put = self._inqueue.put
842 self._quick_get = self._outqueue.get
843
844 @staticmethod
845 def _help_stuff_finish(inqueue, task_handler, size):
Antoine Pitrouab745042018-01-18 10:38:03 +0100846 # drain inqueue, and put sentinels at its head to make workers finish
847 try:
848 while True:
849 inqueue.get(block=False)
850 except queue.Empty:
851 pass
852 for i in range(size):
853 inqueue.put(None)