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