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