Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1 | # |
| 2 | # Module providing the `Pool` class for managing a process pool |
| 3 | # |
| 4 | # multiprocessing/pool.py |
| 5 | # |
R. David Murray | 3fc969a | 2010-12-14 01:38:16 +0000 | [diff] [blame] | 6 | # Copyright (c) 2006-2008, R Oudkerk |
Richard Oudkerk | 3e268aa | 2012-04-30 12:13:55 +0100 | [diff] [blame] | 7 | # Licensed to PSF under a Contributor Agreement. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 8 | # |
| 9 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 10 | __all__ = ['Pool', 'ThreadPool'] |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 11 | |
| 12 | # |
| 13 | # Imports |
| 14 | # |
| 15 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 16 | import collections |
Victor Stinner | 9a8d1d7 | 2018-12-20 20:33:51 +0100 | [diff] [blame] | 17 | import itertools |
Charles-François Natali | 37cfb0a | 2013-06-28 19:25:45 +0200 | [diff] [blame] | 18 | import os |
Victor Stinner | 9a8d1d7 | 2018-12-20 20:33:51 +0100 | [diff] [blame] | 19 | import queue |
| 20 | import threading |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 21 | import time |
Richard Oudkerk | 8575783 | 2013-05-06 11:38:25 +0100 | [diff] [blame] | 22 | import traceback |
Batuhan Taşkaya | 0361556 | 2020-04-10 17:46:36 +0300 | [diff] [blame] | 23 | import types |
Victor Stinner | 9a8d1d7 | 2018-12-20 20:33:51 +0100 | [diff] [blame] | 24 | import warnings |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 25 | from queue import Empty |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 26 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 27 | # If threading is available then ThreadPool should be provided. Therefore |
| 28 | # we avoid top-level imports which are liable to fail on some systems. |
| 29 | from . import util |
Victor Stinner | 7fa767e | 2014-03-20 09:16:38 +0100 | [diff] [blame] | 30 | from . import get_context, TimeoutError |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 31 | from .connection import wait |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 32 | |
| 33 | # |
| 34 | # Constants representing the state of a pool |
| 35 | # |
| 36 | |
Victor Stinner | 9a8d1d7 | 2018-12-20 20:33:51 +0100 | [diff] [blame] | 37 | INIT = "INIT" |
Victor Stinner | 2b417fb | 2018-12-14 11:13:18 +0100 | [diff] [blame] | 38 | RUN = "RUN" |
| 39 | CLOSE = "CLOSE" |
| 40 | TERMINATE = "TERMINATE" |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 41 | |
| 42 | # |
| 43 | # Miscellaneous |
| 44 | # |
| 45 | |
| 46 | job_counter = itertools.count() |
| 47 | |
| 48 | def mapstar(args): |
| 49 | return list(map(*args)) |
| 50 | |
Antoine Pitrou | de911b2 | 2011-12-21 11:03:24 +0100 | [diff] [blame] | 51 | def starmapstar(args): |
| 52 | return list(itertools.starmap(args[0], args[1])) |
| 53 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 54 | # |
Richard Oudkerk | 8575783 | 2013-05-06 11:38:25 +0100 | [diff] [blame] | 55 | # Hack to embed stringification of remote traceback in local traceback |
| 56 | # |
| 57 | |
| 58 | class RemoteTraceback(Exception): |
| 59 | def __init__(self, tb): |
| 60 | self.tb = tb |
| 61 | def __str__(self): |
| 62 | return self.tb |
| 63 | |
| 64 | class ExceptionWithTraceback: |
| 65 | def __init__(self, exc, tb): |
| 66 | tb = traceback.format_exception(type(exc), exc, tb) |
| 67 | tb = ''.join(tb) |
| 68 | self.exc = exc |
| 69 | self.tb = '\n"""\n%s"""' % tb |
| 70 | def __reduce__(self): |
| 71 | return rebuild_exc, (self.exc, self.tb) |
| 72 | |
| 73 | def rebuild_exc(exc, tb): |
| 74 | exc.__cause__ = RemoteTraceback(tb) |
| 75 | return exc |
| 76 | |
| 77 | # |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 78 | # Code run by worker processes |
| 79 | # |
| 80 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 81 | class MaybeEncodingError(Exception): |
| 82 | """Wraps possible unpickleable errors, so they can be |
| 83 | safely sent through the socket.""" |
| 84 | |
| 85 | def __init__(self, exc, value): |
| 86 | self.exc = repr(exc) |
| 87 | self.value = repr(value) |
| 88 | super(MaybeEncodingError, self).__init__(self.exc, self.value) |
| 89 | |
| 90 | def __str__(self): |
| 91 | return "Error sending result: '%s'. Reason: '%s'" % (self.value, |
| 92 | self.exc) |
| 93 | |
| 94 | def __repr__(self): |
Serhiy Storchaka | 465e60e | 2014-07-25 23:36:00 +0300 | [diff] [blame] | 95 | return "<%s: %s>" % (self.__class__.__name__, self) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 96 | |
| 97 | |
Richard Oudkerk | 80a5be1 | 2014-03-23 12:30:54 +0000 | [diff] [blame] | 98 | def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None, |
| 99 | wrap_exception=False): |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 100 | if (maxtasks is not None) and not (isinstance(maxtasks, int) |
| 101 | and maxtasks >= 1): |
| 102 | raise AssertionError("Maxtasks {!r} is not valid".format(maxtasks)) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 103 | put = outqueue.put |
| 104 | get = inqueue.get |
| 105 | if hasattr(inqueue, '_writer'): |
| 106 | inqueue._writer.close() |
| 107 | outqueue._reader.close() |
| 108 | |
| 109 | if initializer is not None: |
| 110 | initializer(*initargs) |
| 111 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 112 | completed = 0 |
| 113 | while maxtasks is None or (maxtasks and completed < maxtasks): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 114 | try: |
| 115 | task = get() |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 116 | except (EOFError, OSError): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 117 | util.debug('worker got EOFError or OSError -- exiting') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 118 | break |
| 119 | |
| 120 | if task is None: |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 121 | util.debug('worker got sentinel -- exiting') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 122 | break |
| 123 | |
| 124 | job, i, func, args, kwds = task |
| 125 | try: |
| 126 | result = (True, func(*args, **kwds)) |
| 127 | except Exception as e: |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 128 | if wrap_exception and func is not _helper_reraises_exception: |
Richard Oudkerk | 80a5be1 | 2014-03-23 12:30:54 +0000 | [diff] [blame] | 129 | e = ExceptionWithTraceback(e, e.__traceback__) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 130 | result = (False, e) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 131 | try: |
| 132 | put((job, i, result)) |
| 133 | except Exception as e: |
| 134 | wrapped = MaybeEncodingError(e, result[1]) |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 135 | util.debug("Possible encoding error while sending result: %s" % ( |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 136 | wrapped)) |
| 137 | put((job, i, (False, wrapped))) |
Antoine Pitrou | 8988945 | 2017-03-24 13:52:11 +0100 | [diff] [blame] | 138 | |
| 139 | task = job = result = func = args = kwds = None |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 140 | completed += 1 |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 141 | util.debug('worker exiting after %d tasks' % completed) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 142 | |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 143 | def _helper_reraises_exception(ex): |
| 144 | 'Pickle-able helper function for use by _guarded_task_generation.' |
| 145 | raise ex |
| 146 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 147 | # |
| 148 | # Class representing a process pool |
| 149 | # |
| 150 | |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 151 | class _PoolCache(dict): |
| 152 | """ |
| 153 | Class that implements a cache for the Pool class that will notify |
| 154 | the pool management threads every time the cache is emptied. The |
| 155 | notification is done by the use of a queue that is provided when |
| 156 | instantiating the cache. |
| 157 | """ |
Serhiy Storchaka | 2085bd0 | 2019-06-01 11:00:15 +0300 | [diff] [blame] | 158 | def __init__(self, /, *args, notifier=None, **kwds): |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 159 | self.notifier = notifier |
| 160 | super().__init__(*args, **kwds) |
| 161 | |
| 162 | def __delitem__(self, item): |
| 163 | super().__delitem__(item) |
| 164 | |
| 165 | # Notify that the cache is empty. This is important because the |
| 166 | # pool keeps maintaining workers until the cache gets drained. This |
| 167 | # eliminates a race condition in which a task is finished after the |
| 168 | # the pool's _handle_workers method has enter another iteration of the |
| 169 | # loop. In this situation, the only event that can wake up the pool |
| 170 | # is the cache to be emptied (no more tasks available). |
| 171 | if not self: |
| 172 | self.notifier.put(None) |
| 173 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 174 | class Pool(object): |
| 175 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 176 | Class which supports an async version of applying functions to arguments. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 177 | ''' |
Richard Oudkerk | 80a5be1 | 2014-03-23 12:30:54 +0000 | [diff] [blame] | 178 | _wrap_exception = True |
| 179 | |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 180 | @staticmethod |
| 181 | def Process(ctx, *args, **kwds): |
| 182 | return ctx.Process(*args, **kwds) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 183 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 184 | def __init__(self, processes=None, initializer=None, initargs=(), |
Richard Oudkerk | b1694cf | 2013-10-16 16:41:56 +0100 | [diff] [blame] | 185 | maxtasksperchild=None, context=None): |
Victor Stinner | 9a8d1d7 | 2018-12-20 20:33:51 +0100 | [diff] [blame] | 186 | # Attributes initialized early to make sure that they exist in |
| 187 | # __del__() if __init__() raises an exception |
| 188 | self._pool = [] |
| 189 | self._state = INIT |
| 190 | |
Richard Oudkerk | b1694cf | 2013-10-16 16:41:56 +0100 | [diff] [blame] | 191 | self._ctx = context or get_context() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 192 | self._setup_queues() |
Antoine Pitrou | ab74504 | 2018-01-18 10:38:03 +0100 | [diff] [blame] | 193 | self._taskqueue = queue.SimpleQueue() |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 194 | # The _change_notifier queue exist to wake up self._handle_workers() |
| 195 | # when the cache (self._cache) is empty or when there is a change in |
| 196 | # the _state variable of the thread that runs _handle_workers. |
| 197 | self._change_notifier = self._ctx.SimpleQueue() |
| 198 | self._cache = _PoolCache(notifier=self._change_notifier) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 199 | self._maxtasksperchild = maxtasksperchild |
| 200 | self._initializer = initializer |
| 201 | self._initargs = initargs |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 202 | |
| 203 | if processes is None: |
Charles-François Natali | 37cfb0a | 2013-06-28 19:25:45 +0200 | [diff] [blame] | 204 | processes = os.cpu_count() or 1 |
Victor Stinner | 2fae27b | 2011-06-20 17:53:35 +0200 | [diff] [blame] | 205 | if processes < 1: |
| 206 | raise ValueError("Number of processes must be at least 1") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 207 | |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 208 | if initializer is not None and not callable(initializer): |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 209 | raise TypeError('initializer must be a callable') |
| 210 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 211 | self._processes = processes |
Julien Palard | 5d236ca | 2018-11-04 23:40:32 +0100 | [diff] [blame] | 212 | try: |
| 213 | self._repopulate_pool() |
| 214 | except Exception: |
| 215 | for p in self._pool: |
| 216 | if p.exitcode is None: |
| 217 | p.terminate() |
| 218 | for p in self._pool: |
| 219 | p.join() |
| 220 | raise |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 221 | |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 222 | sentinels = self._get_sentinels() |
| 223 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 224 | self._worker_handler = threading.Thread( |
| 225 | target=Pool._handle_workers, |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 226 | args=(self._cache, self._taskqueue, self._ctx, self.Process, |
| 227 | self._processes, self._pool, self._inqueue, self._outqueue, |
| 228 | self._initializer, self._initargs, self._maxtasksperchild, |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 229 | self._wrap_exception, sentinels, self._change_notifier) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 230 | ) |
| 231 | self._worker_handler.daemon = True |
| 232 | self._worker_handler._state = RUN |
| 233 | self._worker_handler.start() |
| 234 | |
Victor Stinner | 9dfc754 | 2018-12-06 08:51:47 +0100 | [diff] [blame] | 235 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 236 | self._task_handler = threading.Thread( |
| 237 | target=Pool._handle_tasks, |
Richard Oudkerk | e90cedb | 2013-10-28 23:11:58 +0000 | [diff] [blame] | 238 | args=(self._taskqueue, self._quick_put, self._outqueue, |
| 239 | self._pool, self._cache) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 240 | ) |
Benjamin Peterson | fae4c62 | 2008-08-18 18:40:08 +0000 | [diff] [blame] | 241 | self._task_handler.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 242 | self._task_handler._state = RUN |
| 243 | self._task_handler.start() |
| 244 | |
| 245 | self._result_handler = threading.Thread( |
| 246 | target=Pool._handle_results, |
| 247 | args=(self._outqueue, self._quick_get, self._cache) |
| 248 | ) |
Benjamin Peterson | fae4c62 | 2008-08-18 18:40:08 +0000 | [diff] [blame] | 249 | self._result_handler.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 250 | self._result_handler._state = RUN |
| 251 | self._result_handler.start() |
| 252 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 253 | self._terminate = util.Finalize( |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 254 | self, self._terminate_pool, |
| 255 | args=(self._taskqueue, self._inqueue, self._outqueue, self._pool, |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 256 | self._change_notifier, self._worker_handler, self._task_handler, |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 257 | self._result_handler, self._cache), |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 258 | exitpriority=15 |
| 259 | ) |
Victor Stinner | 9a8d1d7 | 2018-12-20 20:33:51 +0100 | [diff] [blame] | 260 | self._state = RUN |
| 261 | |
| 262 | # Copy globals as function locals to make sure that they are available |
| 263 | # during Python shutdown when the Pool is destroyed. |
| 264 | def __del__(self, _warn=warnings.warn, RUN=RUN): |
| 265 | if self._state == RUN: |
| 266 | _warn(f"unclosed running multiprocessing pool {self!r}", |
| 267 | ResourceWarning, source=self) |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 268 | if getattr(self, '_change_notifier', None) is not None: |
| 269 | self._change_notifier.put(None) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 270 | |
Victor Stinner | 2b417fb | 2018-12-14 11:13:18 +0100 | [diff] [blame] | 271 | def __repr__(self): |
| 272 | cls = self.__class__ |
| 273 | return (f'<{cls.__module__}.{cls.__qualname__} ' |
| 274 | f'state={self._state} ' |
| 275 | f'pool_size={len(self._pool)}>') |
| 276 | |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 277 | def _get_sentinels(self): |
| 278 | task_queue_sentinels = [self._outqueue._reader] |
| 279 | self_notifier_sentinels = [self._change_notifier._reader] |
| 280 | return [*task_queue_sentinels, *self_notifier_sentinels] |
| 281 | |
| 282 | @staticmethod |
| 283 | def _get_worker_sentinels(workers): |
| 284 | return [worker.sentinel for worker in |
| 285 | workers if hasattr(worker, "sentinel")] |
| 286 | |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 287 | @staticmethod |
| 288 | def _join_exited_workers(pool): |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 289 | """Cleanup after any worker processes which have exited due to reaching |
| 290 | their specified lifetime. Returns True if any workers were cleaned up. |
| 291 | """ |
| 292 | cleaned = False |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 293 | for i in reversed(range(len(pool))): |
| 294 | worker = pool[i] |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 295 | if worker.exitcode is not None: |
| 296 | # worker exited |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 297 | util.debug('cleaning up worker %d' % i) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 298 | worker.join() |
| 299 | cleaned = True |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 300 | del pool[i] |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 301 | return cleaned |
| 302 | |
| 303 | def _repopulate_pool(self): |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 304 | return self._repopulate_pool_static(self._ctx, self.Process, |
| 305 | self._processes, |
| 306 | self._pool, self._inqueue, |
| 307 | self._outqueue, self._initializer, |
| 308 | self._initargs, |
| 309 | self._maxtasksperchild, |
| 310 | self._wrap_exception) |
| 311 | |
| 312 | @staticmethod |
| 313 | def _repopulate_pool_static(ctx, Process, processes, pool, inqueue, |
| 314 | outqueue, initializer, initargs, |
| 315 | maxtasksperchild, wrap_exception): |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 316 | """Bring the number of pool processes up to the specified number, |
| 317 | for use after reaping workers which have exited. |
| 318 | """ |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 319 | for i in range(processes - len(pool)): |
| 320 | w = Process(ctx, target=worker, |
| 321 | args=(inqueue, outqueue, |
| 322 | initializer, |
| 323 | initargs, maxtasksperchild, |
| 324 | wrap_exception)) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 325 | w.name = w.name.replace('Process', 'PoolWorker') |
| 326 | w.daemon = True |
| 327 | w.start() |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 328 | pool.append(w) |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 329 | util.debug('added worker') |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 330 | |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 331 | @staticmethod |
| 332 | def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue, |
| 333 | initializer, initargs, maxtasksperchild, |
| 334 | wrap_exception): |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 335 | """Clean up any exited workers and start replacements for them. |
| 336 | """ |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 337 | if Pool._join_exited_workers(pool): |
| 338 | Pool._repopulate_pool_static(ctx, Process, processes, pool, |
| 339 | inqueue, outqueue, initializer, |
| 340 | initargs, maxtasksperchild, |
| 341 | wrap_exception) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 342 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 343 | def _setup_queues(self): |
Richard Oudkerk | b1694cf | 2013-10-16 16:41:56 +0100 | [diff] [blame] | 344 | self._inqueue = self._ctx.SimpleQueue() |
| 345 | self._outqueue = self._ctx.SimpleQueue() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 346 | self._quick_put = self._inqueue._writer.send |
| 347 | self._quick_get = self._outqueue._reader.recv |
| 348 | |
Victor Stinner | 08c2ba0 | 2018-12-13 02:15:30 +0100 | [diff] [blame] | 349 | def _check_running(self): |
| 350 | if self._state != RUN: |
| 351 | raise ValueError("Pool not running") |
| 352 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 353 | def apply(self, func, args=(), kwds={}): |
| 354 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 355 | Equivalent of `func(*args, **kwds)`. |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 356 | Pool must be running. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 357 | ''' |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 358 | return self.apply_async(func, args, kwds).get() |
| 359 | |
| 360 | def map(self, func, iterable, chunksize=None): |
| 361 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 362 | Apply `func` to each element in `iterable`, collecting the results |
| 363 | in a list that is returned. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 364 | ''' |
Antoine Pitrou | de911b2 | 2011-12-21 11:03:24 +0100 | [diff] [blame] | 365 | return self._map_async(func, iterable, mapstar, chunksize).get() |
| 366 | |
| 367 | def starmap(self, func, iterable, chunksize=None): |
| 368 | ''' |
| 369 | Like `map()` method but the elements of the `iterable` are expected to |
| 370 | be iterables as well and will be unpacked as arguments. Hence |
| 371 | `func` and (a, b) becomes func(a, b). |
| 372 | ''' |
Antoine Pitrou | de911b2 | 2011-12-21 11:03:24 +0100 | [diff] [blame] | 373 | return self._map_async(func, iterable, starmapstar, chunksize).get() |
| 374 | |
| 375 | def starmap_async(self, func, iterable, chunksize=None, callback=None, |
| 376 | error_callback=None): |
| 377 | ''' |
| 378 | Asynchronous version of `starmap()` method. |
| 379 | ''' |
Antoine Pitrou | de911b2 | 2011-12-21 11:03:24 +0100 | [diff] [blame] | 380 | return self._map_async(func, iterable, starmapstar, chunksize, |
| 381 | callback, error_callback) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 382 | |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 383 | def _guarded_task_generation(self, result_job, func, iterable): |
| 384 | '''Provides a generator of tasks for imap and imap_unordered with |
| 385 | appropriate handling for iterables which throw exceptions during |
| 386 | iteration.''' |
| 387 | try: |
| 388 | i = -1 |
| 389 | for i, x in enumerate(iterable): |
| 390 | yield (result_job, i, func, (x,), {}) |
| 391 | except Exception as e: |
| 392 | yield (result_job, i+1, _helper_reraises_exception, (e,), {}) |
| 393 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 394 | def imap(self, func, iterable, chunksize=1): |
| 395 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 396 | Equivalent of `map()` -- can be MUCH slower than `Pool.map()`. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 397 | ''' |
Victor Stinner | 08c2ba0 | 2018-12-13 02:15:30 +0100 | [diff] [blame] | 398 | self._check_running() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 399 | if chunksize == 1: |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 400 | result = IMapIterator(self) |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 401 | self._taskqueue.put( |
| 402 | ( |
| 403 | self._guarded_task_generation(result._job, func, iterable), |
| 404 | result._set_length |
| 405 | )) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 406 | return result |
| 407 | else: |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 408 | if chunksize < 1: |
| 409 | raise ValueError( |
| 410 | "Chunksize must be 1+, not {0:n}".format( |
| 411 | chunksize)) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 412 | task_batches = Pool._get_tasks(func, iterable, chunksize) |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 413 | result = IMapIterator(self) |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 414 | self._taskqueue.put( |
| 415 | ( |
| 416 | self._guarded_task_generation(result._job, |
| 417 | mapstar, |
| 418 | task_batches), |
| 419 | result._set_length |
| 420 | )) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 421 | return (item for chunk in result for item in chunk) |
| 422 | |
| 423 | def imap_unordered(self, func, iterable, chunksize=1): |
| 424 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 425 | Like `imap()` method but ordering of results is arbitrary. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 426 | ''' |
Victor Stinner | 08c2ba0 | 2018-12-13 02:15:30 +0100 | [diff] [blame] | 427 | self._check_running() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 428 | if chunksize == 1: |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 429 | result = IMapUnorderedIterator(self) |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 430 | self._taskqueue.put( |
| 431 | ( |
| 432 | self._guarded_task_generation(result._job, func, iterable), |
| 433 | result._set_length |
| 434 | )) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 435 | return result |
| 436 | else: |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 437 | if chunksize < 1: |
| 438 | raise ValueError( |
| 439 | "Chunksize must be 1+, not {0!r}".format(chunksize)) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 440 | task_batches = Pool._get_tasks(func, iterable, chunksize) |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 441 | result = IMapUnorderedIterator(self) |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 442 | self._taskqueue.put( |
| 443 | ( |
| 444 | self._guarded_task_generation(result._job, |
| 445 | mapstar, |
| 446 | task_batches), |
| 447 | result._set_length |
| 448 | )) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 449 | return (item for chunk in result for item in chunk) |
| 450 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 451 | def apply_async(self, func, args=(), kwds={}, callback=None, |
| 452 | error_callback=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 453 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 454 | Asynchronous version of `apply()` method. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 455 | ''' |
Victor Stinner | 08c2ba0 | 2018-12-13 02:15:30 +0100 | [diff] [blame] | 456 | self._check_running() |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 457 | result = ApplyResult(self, callback, error_callback) |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 458 | self._taskqueue.put(([(result._job, 0, func, args, kwds)], None)) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 459 | return result |
| 460 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 461 | def map_async(self, func, iterable, chunksize=None, callback=None, |
| 462 | error_callback=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 463 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 464 | Asynchronous version of `map()` method. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 465 | ''' |
Hynek Schlawack | 254af26 | 2012-10-27 12:53:02 +0200 | [diff] [blame] | 466 | return self._map_async(func, iterable, mapstar, chunksize, callback, |
| 467 | error_callback) |
Antoine Pitrou | de911b2 | 2011-12-21 11:03:24 +0100 | [diff] [blame] | 468 | |
| 469 | def _map_async(self, func, iterable, mapper, chunksize=None, callback=None, |
| 470 | error_callback=None): |
| 471 | ''' |
| 472 | Helper function to implement map, starmap and their async counterparts. |
| 473 | ''' |
Victor Stinner | 08c2ba0 | 2018-12-13 02:15:30 +0100 | [diff] [blame] | 474 | self._check_running() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 475 | if not hasattr(iterable, '__len__'): |
| 476 | iterable = list(iterable) |
| 477 | |
| 478 | if chunksize is None: |
| 479 | chunksize, extra = divmod(len(iterable), len(self._pool) * 4) |
| 480 | if extra: |
| 481 | chunksize += 1 |
Alexandre Vassalotti | e52e378 | 2009-07-17 09:18:18 +0000 | [diff] [blame] | 482 | if len(iterable) == 0: |
| 483 | chunksize = 0 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 484 | |
| 485 | task_batches = Pool._get_tasks(func, iterable, chunksize) |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 486 | result = MapResult(self, chunksize, len(iterable), callback, |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 487 | error_callback=error_callback) |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 488 | self._taskqueue.put( |
| 489 | ( |
| 490 | self._guarded_task_generation(result._job, |
| 491 | mapper, |
| 492 | task_batches), |
| 493 | None |
| 494 | ) |
| 495 | ) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 496 | return result |
| 497 | |
| 498 | @staticmethod |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 499 | def _wait_for_updates(sentinels, change_notifier, timeout=None): |
| 500 | wait(sentinels, timeout=timeout) |
| 501 | while not change_notifier.empty(): |
| 502 | change_notifier.get() |
| 503 | |
| 504 | @classmethod |
| 505 | def _handle_workers(cls, cache, taskqueue, ctx, Process, processes, |
| 506 | pool, inqueue, outqueue, initializer, initargs, |
| 507 | maxtasksperchild, wrap_exception, sentinels, |
| 508 | change_notifier): |
Charles-François Natali | f8859e1 | 2011-10-24 18:45:29 +0200 | [diff] [blame] | 509 | thread = threading.current_thread() |
| 510 | |
| 511 | # Keep maintaining workers until the cache gets drained, unless the pool |
| 512 | # is terminated. |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 513 | while thread._state == RUN or (cache and thread._state != TERMINATE): |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 514 | cls._maintain_pool(ctx, Process, processes, pool, inqueue, |
| 515 | outqueue, initializer, initargs, |
| 516 | maxtasksperchild, wrap_exception) |
| 517 | |
| 518 | current_sentinels = [*cls._get_worker_sentinels(pool), *sentinels] |
| 519 | |
| 520 | cls._wait_for_updates(current_sentinels, change_notifier) |
Antoine Pitrou | 81dee6b | 2011-04-11 00:18:59 +0200 | [diff] [blame] | 521 | # send sentinel to stop workers |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 522 | taskqueue.put(None) |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 523 | util.debug('worker handler exiting') |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 524 | |
| 525 | @staticmethod |
Richard Oudkerk | e90cedb | 2013-10-28 23:11:58 +0000 | [diff] [blame] | 526 | def _handle_tasks(taskqueue, put, outqueue, pool, cache): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 527 | thread = threading.current_thread() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 528 | |
| 529 | for taskseq, set_length in iter(taskqueue.get, None): |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 530 | task = None |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 531 | try: |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 532 | # iterating taskseq cannot fail |
| 533 | for task in taskseq: |
Victor Stinner | 2b417fb | 2018-12-14 11:13:18 +0100 | [diff] [blame] | 534 | if thread._state != RUN: |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 535 | util.debug('task handler found thread._state != RUN') |
| 536 | break |
Richard Oudkerk | e90cedb | 2013-10-28 23:11:58 +0000 | [diff] [blame] | 537 | try: |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 538 | put(task) |
| 539 | except Exception as e: |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 540 | job, idx = task[:2] |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 541 | try: |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 542 | cache[job]._set(idx, (False, e)) |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 543 | except KeyError: |
| 544 | pass |
| 545 | else: |
| 546 | if set_length: |
| 547 | util.debug('doing set_length()') |
Xiang Zhang | 794623b | 2017-03-29 11:58:54 +0800 | [diff] [blame] | 548 | idx = task[1] if task else -1 |
| 549 | set_length(idx + 1) |
Serhiy Storchaka | 79fbeee | 2015-03-13 08:25:26 +0200 | [diff] [blame] | 550 | continue |
| 551 | break |
Antoine Pitrou | 8988945 | 2017-03-24 13:52:11 +0100 | [diff] [blame] | 552 | finally: |
| 553 | task = taskseq = job = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 554 | else: |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 555 | util.debug('task handler got sentinel') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 556 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 557 | try: |
| 558 | # tell result handler to finish when cache is empty |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 559 | util.debug('task handler sending sentinel to result handler') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 560 | outqueue.put(None) |
| 561 | |
| 562 | # tell workers there is no more work |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 563 | util.debug('task handler sending sentinel to workers') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 564 | for p in pool: |
| 565 | put(None) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 566 | except OSError: |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 567 | util.debug('task handler got OSError when sending sentinels') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 568 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 569 | util.debug('task handler exiting') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 570 | |
| 571 | @staticmethod |
| 572 | def _handle_results(outqueue, get, cache): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 573 | thread = threading.current_thread() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 574 | |
| 575 | while 1: |
| 576 | try: |
| 577 | task = get() |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 578 | except (OSError, EOFError): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 579 | util.debug('result handler got EOFError/OSError -- exiting') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 580 | return |
| 581 | |
Victor Stinner | 2dfe351 | 2018-12-16 23:40:49 +0100 | [diff] [blame] | 582 | if thread._state != RUN: |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 583 | assert thread._state == TERMINATE, "Thread not in TERMINATE" |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 584 | util.debug('result handler found thread._state=TERMINATE') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 585 | break |
| 586 | |
| 587 | if task is None: |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 588 | util.debug('result handler got sentinel') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 589 | break |
| 590 | |
| 591 | job, i, obj = task |
| 592 | try: |
| 593 | cache[job]._set(i, obj) |
| 594 | except KeyError: |
| 595 | pass |
Antoine Pitrou | 8988945 | 2017-03-24 13:52:11 +0100 | [diff] [blame] | 596 | task = job = obj = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 597 | |
| 598 | while cache and thread._state != TERMINATE: |
| 599 | try: |
| 600 | task = get() |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 601 | except (OSError, EOFError): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 602 | util.debug('result handler got EOFError/OSError -- exiting') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 603 | return |
| 604 | |
| 605 | if task is None: |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 606 | util.debug('result handler ignoring extra sentinel') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 607 | continue |
| 608 | job, i, obj = task |
| 609 | try: |
| 610 | cache[job]._set(i, obj) |
| 611 | except KeyError: |
| 612 | pass |
Antoine Pitrou | 8988945 | 2017-03-24 13:52:11 +0100 | [diff] [blame] | 613 | task = job = obj = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 614 | |
| 615 | if hasattr(outqueue, '_reader'): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 616 | util.debug('ensuring that outqueue is not full') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 617 | # If we don't make room available in outqueue then |
| 618 | # attempts to add the sentinel (None) to outqueue may |
| 619 | # block. There is guaranteed to be no more than 2 sentinels. |
| 620 | try: |
| 621 | for i in range(10): |
| 622 | if not outqueue._reader.poll(): |
| 623 | break |
| 624 | get() |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 625 | except (OSError, EOFError): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 626 | pass |
| 627 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 628 | util.debug('result handler exiting: len(cache)=%s, thread._state=%s', |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 629 | len(cache), thread._state) |
| 630 | |
| 631 | @staticmethod |
| 632 | def _get_tasks(func, it, size): |
| 633 | it = iter(it) |
| 634 | while 1: |
| 635 | x = tuple(itertools.islice(it, size)) |
| 636 | if not x: |
| 637 | return |
| 638 | yield (func, x) |
| 639 | |
| 640 | def __reduce__(self): |
| 641 | raise NotImplementedError( |
| 642 | 'pool objects cannot be passed between processes or pickled' |
| 643 | ) |
| 644 | |
| 645 | def close(self): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 646 | util.debug('closing pool') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 647 | if self._state == RUN: |
| 648 | self._state = CLOSE |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 649 | self._worker_handler._state = CLOSE |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 650 | self._change_notifier.put(None) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 651 | |
| 652 | def terminate(self): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 653 | util.debug('terminating pool') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 654 | self._state = TERMINATE |
| 655 | self._terminate() |
| 656 | |
| 657 | def join(self): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 658 | util.debug('joining pool') |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 659 | if self._state == RUN: |
| 660 | raise ValueError("Pool is still running") |
| 661 | elif self._state not in (CLOSE, TERMINATE): |
| 662 | raise ValueError("In unknown state") |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 663 | self._worker_handler.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 664 | self._task_handler.join() |
| 665 | self._result_handler.join() |
| 666 | for p in self._pool: |
| 667 | p.join() |
| 668 | |
| 669 | @staticmethod |
| 670 | def _help_stuff_finish(inqueue, task_handler, size): |
| 671 | # task_handler may be blocked trying to put items on inqueue |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 672 | util.debug('removing tasks from inqueue until task handler finished') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 673 | inqueue._rlock.acquire() |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 674 | while task_handler.is_alive() and inqueue._reader.poll(): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 675 | inqueue._reader.recv() |
| 676 | time.sleep(0) |
| 677 | |
| 678 | @classmethod |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 679 | def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier, |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 680 | worker_handler, task_handler, result_handler, cache): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 681 | # this is guaranteed to only be called once |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 682 | util.debug('finalizing pool') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 683 | |
Batuhan Taşkaya | ac10e0c | 2020-03-15 22:45:56 +0300 | [diff] [blame] | 684 | # Notify that the worker_handler state has been changed so the |
| 685 | # _handle_workers loop can be unblocked (and exited) in order to |
| 686 | # send the finalization sentinel all the workers. |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 687 | worker_handler._state = TERMINATE |
Batuhan Taşkaya | ac10e0c | 2020-03-15 22:45:56 +0300 | [diff] [blame] | 688 | change_notifier.put(None) |
| 689 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 690 | task_handler._state = TERMINATE |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 691 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 692 | util.debug('helping task handler/workers to finish') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 693 | cls._help_stuff_finish(inqueue, task_handler, len(pool)) |
| 694 | |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 695 | if (not result_handler.is_alive()) and (len(cache) != 0): |
| 696 | raise AssertionError( |
| 697 | "Cannot have cache with result_hander not alive") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 698 | |
| 699 | result_handler._state = TERMINATE |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 700 | change_notifier.put(None) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 701 | outqueue.put(None) # sentinel |
| 702 | |
Antoine Pitrou | 81dee6b | 2011-04-11 00:18:59 +0200 | [diff] [blame] | 703 | # We must wait for the worker handler to exit before terminating |
| 704 | # workers because we don't want workers to be restarted behind our back. |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 705 | util.debug('joining worker handler') |
Richard Oudkerk | f29ec4b | 2012-06-18 15:54:57 +0100 | [diff] [blame] | 706 | if threading.current_thread() is not worker_handler: |
| 707 | worker_handler.join() |
Antoine Pitrou | 81dee6b | 2011-04-11 00:18:59 +0200 | [diff] [blame] | 708 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 709 | # Terminate workers which haven't already finished. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 710 | if pool and hasattr(pool[0], 'terminate'): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 711 | util.debug('terminating workers') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 712 | for p in pool: |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 713 | if p.exitcode is None: |
| 714 | p.terminate() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 715 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 716 | util.debug('joining task handler') |
Richard Oudkerk | f29ec4b | 2012-06-18 15:54:57 +0100 | [diff] [blame] | 717 | if threading.current_thread() is not task_handler: |
| 718 | task_handler.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 719 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 720 | util.debug('joining result handler') |
Richard Oudkerk | f29ec4b | 2012-06-18 15:54:57 +0100 | [diff] [blame] | 721 | if threading.current_thread() is not result_handler: |
| 722 | result_handler.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 723 | |
| 724 | if pool and hasattr(pool[0], 'terminate'): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 725 | util.debug('joining pool workers') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 726 | for p in pool: |
Florent Xicluna | 998171f | 2010-03-08 13:32:17 +0000 | [diff] [blame] | 727 | if p.is_alive(): |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 728 | # worker has not yet exited |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 729 | util.debug('cleaning up worker %d' % p.pid) |
Florent Xicluna | 998171f | 2010-03-08 13:32:17 +0000 | [diff] [blame] | 730 | p.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 731 | |
Richard Oudkerk | d69cfe8 | 2012-06-18 17:47:52 +0100 | [diff] [blame] | 732 | def __enter__(self): |
Victor Stinner | 08c2ba0 | 2018-12-13 02:15:30 +0100 | [diff] [blame] | 733 | self._check_running() |
Richard Oudkerk | d69cfe8 | 2012-06-18 17:47:52 +0100 | [diff] [blame] | 734 | return self |
| 735 | |
| 736 | def __exit__(self, exc_type, exc_val, exc_tb): |
| 737 | self.terminate() |
| 738 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 739 | # |
| 740 | # Class whose instances are returned by `Pool.apply_async()` |
| 741 | # |
| 742 | |
| 743 | class ApplyResult(object): |
| 744 | |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 745 | def __init__(self, pool, callback, error_callback): |
| 746 | self._pool = pool |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 747 | self._event = threading.Event() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 748 | self._job = next(job_counter) |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 749 | self._cache = pool._cache |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 750 | self._callback = callback |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 751 | self._error_callback = error_callback |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 752 | self._cache[self._job] = self |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 753 | |
| 754 | def ready(self): |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 755 | return self._event.is_set() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 756 | |
| 757 | def successful(self): |
Allen W. Smith, Ph.D | bd73e72 | 2017-08-29 17:52:18 -0500 | [diff] [blame] | 758 | if not self.ready(): |
| 759 | raise ValueError("{0!r} not ready".format(self)) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 760 | return self._success |
| 761 | |
| 762 | def wait(self, timeout=None): |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 763 | self._event.wait(timeout) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 764 | |
| 765 | def get(self, timeout=None): |
| 766 | self.wait(timeout) |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 767 | if not self.ready(): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 768 | raise TimeoutError |
| 769 | if self._success: |
| 770 | return self._value |
| 771 | else: |
| 772 | raise self._value |
| 773 | |
| 774 | def _set(self, i, obj): |
| 775 | self._success, self._value = obj |
| 776 | if self._callback and self._success: |
| 777 | self._callback(self._value) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 778 | if self._error_callback and not self._success: |
| 779 | self._error_callback(self._value) |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 780 | self._event.set() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 781 | del self._cache[self._job] |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 782 | self._pool = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 783 | |
Batuhan Taşkaya | 0361556 | 2020-04-10 17:46:36 +0300 | [diff] [blame] | 784 | __class_getitem__ = classmethod(types.GenericAlias) |
| 785 | |
Richard Oudkerk | def51ca | 2013-05-06 12:10:04 +0100 | [diff] [blame] | 786 | AsyncResult = ApplyResult # create alias -- see #17805 |
| 787 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 788 | # |
| 789 | # Class whose instances are returned by `Pool.map_async()` |
| 790 | # |
| 791 | |
| 792 | class MapResult(ApplyResult): |
| 793 | |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 794 | def __init__(self, pool, chunksize, length, callback, error_callback): |
| 795 | ApplyResult.__init__(self, pool, callback, |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 796 | error_callback=error_callback) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 797 | self._success = True |
| 798 | self._value = [None] * length |
| 799 | self._chunksize = chunksize |
| 800 | if chunksize <= 0: |
| 801 | self._number_left = 0 |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 802 | self._event.set() |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 803 | del self._cache[self._job] |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 804 | else: |
| 805 | self._number_left = length//chunksize + bool(length % chunksize) |
| 806 | |
| 807 | def _set(self, i, success_result): |
Charles-François Natali | 78f55ff | 2016-02-10 22:58:18 +0000 | [diff] [blame] | 808 | self._number_left -= 1 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 809 | success, result = success_result |
Charles-François Natali | 78f55ff | 2016-02-10 22:58:18 +0000 | [diff] [blame] | 810 | if success and self._success: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 811 | self._value[i*self._chunksize:(i+1)*self._chunksize] = result |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 812 | if self._number_left == 0: |
| 813 | if self._callback: |
| 814 | self._callback(self._value) |
| 815 | del self._cache[self._job] |
Richard Oudkerk | 692130a | 2012-05-25 13:26:53 +0100 | [diff] [blame] | 816 | self._event.set() |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 817 | self._pool = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 818 | else: |
Charles-François Natali | 78f55ff | 2016-02-10 22:58:18 +0000 | [diff] [blame] | 819 | if not success and self._success: |
| 820 | # only store first exception |
| 821 | self._success = False |
| 822 | self._value = result |
| 823 | if self._number_left == 0: |
| 824 | # only consider the result ready once all jobs are done |
| 825 | if self._error_callback: |
| 826 | self._error_callback(self._value) |
| 827 | del self._cache[self._job] |
| 828 | self._event.set() |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 829 | self._pool = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 830 | |
| 831 | # |
| 832 | # Class whose instances are returned by `Pool.imap()` |
| 833 | # |
| 834 | |
| 835 | class IMapIterator(object): |
| 836 | |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 837 | def __init__(self, pool): |
| 838 | self._pool = pool |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 839 | self._cond = threading.Condition(threading.Lock()) |
| 840 | self._job = next(job_counter) |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 841 | self._cache = pool._cache |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 842 | self._items = collections.deque() |
| 843 | self._index = 0 |
| 844 | self._length = None |
| 845 | self._unsorted = {} |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 846 | self._cache[self._job] = self |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 847 | |
| 848 | def __iter__(self): |
| 849 | return self |
| 850 | |
| 851 | def next(self, timeout=None): |
Charles-François Natali | a924fc7 | 2014-05-25 14:12:12 +0100 | [diff] [blame] | 852 | with self._cond: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 853 | try: |
| 854 | item = self._items.popleft() |
| 855 | except IndexError: |
| 856 | if self._index == self._length: |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 857 | self._pool = None |
Serhiy Storchaka | 5affd23 | 2017-04-05 09:37:24 +0300 | [diff] [blame] | 858 | raise StopIteration from None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 859 | self._cond.wait(timeout) |
| 860 | try: |
| 861 | item = self._items.popleft() |
| 862 | except IndexError: |
| 863 | if self._index == self._length: |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 864 | self._pool = None |
Serhiy Storchaka | 5affd23 | 2017-04-05 09:37:24 +0300 | [diff] [blame] | 865 | raise StopIteration from None |
| 866 | raise TimeoutError from None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 867 | |
| 868 | success, value = item |
| 869 | if success: |
| 870 | return value |
| 871 | raise value |
| 872 | |
| 873 | __next__ = next # XXX |
| 874 | |
| 875 | def _set(self, i, obj): |
Charles-François Natali | a924fc7 | 2014-05-25 14:12:12 +0100 | [diff] [blame] | 876 | with self._cond: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 877 | if self._index == i: |
| 878 | self._items.append(obj) |
| 879 | self._index += 1 |
| 880 | while self._index in self._unsorted: |
| 881 | obj = self._unsorted.pop(self._index) |
| 882 | self._items.append(obj) |
| 883 | self._index += 1 |
| 884 | self._cond.notify() |
| 885 | else: |
| 886 | self._unsorted[i] = obj |
| 887 | |
| 888 | if self._index == self._length: |
| 889 | del self._cache[self._job] |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 890 | self._pool = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 891 | |
| 892 | def _set_length(self, length): |
Charles-François Natali | a924fc7 | 2014-05-25 14:12:12 +0100 | [diff] [blame] | 893 | with self._cond: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 894 | self._length = length |
| 895 | if self._index == self._length: |
| 896 | self._cond.notify() |
| 897 | del self._cache[self._job] |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 898 | self._pool = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 899 | |
| 900 | # |
| 901 | # Class whose instances are returned by `Pool.imap_unordered()` |
| 902 | # |
| 903 | |
| 904 | class IMapUnorderedIterator(IMapIterator): |
| 905 | |
| 906 | def _set(self, i, obj): |
Charles-François Natali | a924fc7 | 2014-05-25 14:12:12 +0100 | [diff] [blame] | 907 | with self._cond: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 908 | self._items.append(obj) |
| 909 | self._index += 1 |
| 910 | self._cond.notify() |
| 911 | if self._index == self._length: |
| 912 | del self._cache[self._job] |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 913 | self._pool = None |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 914 | |
| 915 | # |
| 916 | # |
| 917 | # |
| 918 | |
| 919 | class ThreadPool(Pool): |
Richard Oudkerk | 80a5be1 | 2014-03-23 12:30:54 +0000 | [diff] [blame] | 920 | _wrap_exception = False |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 921 | |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 922 | @staticmethod |
Pablo Galindo | 3766f18 | 2019-02-11 17:29:00 +0000 | [diff] [blame] | 923 | def Process(ctx, *args, **kwds): |
Richard Oudkerk | 84ed9a6 | 2013-08-14 15:35:41 +0100 | [diff] [blame] | 924 | from .dummy import Process |
| 925 | return Process(*args, **kwds) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 926 | |
| 927 | def __init__(self, processes=None, initializer=None, initargs=()): |
| 928 | Pool.__init__(self, processes, initializer, initargs) |
| 929 | |
| 930 | def _setup_queues(self): |
Antoine Pitrou | ab74504 | 2018-01-18 10:38:03 +0100 | [diff] [blame] | 931 | self._inqueue = queue.SimpleQueue() |
| 932 | self._outqueue = queue.SimpleQueue() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 933 | self._quick_put = self._inqueue.put |
| 934 | self._quick_get = self._outqueue.get |
| 935 | |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 936 | def _get_sentinels(self): |
| 937 | return [self._change_notifier._reader] |
| 938 | |
| 939 | @staticmethod |
| 940 | def _get_worker_sentinels(workers): |
| 941 | return [] |
| 942 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 943 | @staticmethod |
| 944 | def _help_stuff_finish(inqueue, task_handler, size): |
Antoine Pitrou | ab74504 | 2018-01-18 10:38:03 +0100 | [diff] [blame] | 945 | # drain inqueue, and put sentinels at its head to make workers finish |
| 946 | try: |
| 947 | while True: |
| 948 | inqueue.get(block=False) |
| 949 | except queue.Empty: |
| 950 | pass |
| 951 | for i in range(size): |
| 952 | inqueue.put(None) |
Pablo Galindo | 7c99454 | 2019-03-16 22:34:24 +0000 | [diff] [blame] | 953 | |
| 954 | def _wait_for_updates(self, sentinels, change_notifier, timeout): |
| 955 | time.sleep(timeout) |