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