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