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 |
| 7 | # All rights reserved. |
| 8 | # |
| 9 | # Redistribution and use in source and binary forms, with or without |
| 10 | # modification, are permitted provided that the following conditions |
| 11 | # are met: |
| 12 | # |
| 13 | # 1. Redistributions of source code must retain the above copyright |
| 14 | # notice, this list of conditions and the following disclaimer. |
| 15 | # 2. Redistributions in binary form must reproduce the above copyright |
| 16 | # notice, this list of conditions and the following disclaimer in the |
| 17 | # documentation and/or other materials provided with the distribution. |
| 18 | # 3. Neither the name of author nor the names of any contributors may be |
| 19 | # used to endorse or promote products derived from this software |
| 20 | # without specific prior written permission. |
| 21 | # |
| 22 | # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND |
| 23 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 24 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 25 | # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE |
| 26 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 27 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS |
| 28 | # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
| 29 | # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 30 | # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| 31 | # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
| 32 | # SUCH DAMAGE. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 33 | # |
| 34 | |
| 35 | __all__ = ['Pool'] |
| 36 | |
| 37 | # |
| 38 | # Imports |
| 39 | # |
| 40 | |
| 41 | import threading |
| 42 | import queue |
| 43 | import itertools |
| 44 | import collections |
| 45 | import time |
| 46 | |
| 47 | from multiprocessing import Process, cpu_count, TimeoutError |
| 48 | from multiprocessing.util import Finalize, debug |
| 49 | |
| 50 | # |
| 51 | # Constants representing the state of a pool |
| 52 | # |
| 53 | |
| 54 | RUN = 0 |
| 55 | CLOSE = 1 |
| 56 | TERMINATE = 2 |
| 57 | |
| 58 | # |
| 59 | # Miscellaneous |
| 60 | # |
| 61 | |
| 62 | job_counter = itertools.count() |
| 63 | |
| 64 | def mapstar(args): |
| 65 | return list(map(*args)) |
| 66 | |
| 67 | # |
| 68 | # Code run by worker processes |
| 69 | # |
| 70 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 71 | class MaybeEncodingError(Exception): |
| 72 | """Wraps possible unpickleable errors, so they can be |
| 73 | safely sent through the socket.""" |
| 74 | |
| 75 | def __init__(self, exc, value): |
| 76 | self.exc = repr(exc) |
| 77 | self.value = repr(value) |
| 78 | super(MaybeEncodingError, self).__init__(self.exc, self.value) |
| 79 | |
| 80 | def __str__(self): |
| 81 | return "Error sending result: '%s'. Reason: '%s'" % (self.value, |
| 82 | self.exc) |
| 83 | |
| 84 | def __repr__(self): |
| 85 | return "<MaybeEncodingError: %s>" % str(self) |
| 86 | |
| 87 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 88 | def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): |
| 89 | assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 90 | put = outqueue.put |
| 91 | get = inqueue.get |
| 92 | if hasattr(inqueue, '_writer'): |
| 93 | inqueue._writer.close() |
| 94 | outqueue._reader.close() |
| 95 | |
| 96 | if initializer is not None: |
| 97 | initializer(*initargs) |
| 98 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 99 | completed = 0 |
| 100 | while maxtasks is None or (maxtasks and completed < maxtasks): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 101 | try: |
| 102 | task = get() |
| 103 | except (EOFError, IOError): |
| 104 | debug('worker got EOFError or IOError -- exiting') |
| 105 | break |
| 106 | |
| 107 | if task is None: |
| 108 | debug('worker got sentinel -- exiting') |
| 109 | break |
| 110 | |
| 111 | job, i, func, args, kwds = task |
| 112 | try: |
| 113 | result = (True, func(*args, **kwds)) |
| 114 | except Exception as e: |
| 115 | result = (False, e) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 116 | try: |
| 117 | put((job, i, result)) |
| 118 | except Exception as e: |
| 119 | wrapped = MaybeEncodingError(e, result[1]) |
| 120 | debug("Possible encoding error while sending result: %s" % ( |
| 121 | wrapped)) |
| 122 | put((job, i, (False, wrapped))) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 123 | completed += 1 |
| 124 | debug('worker exiting after %d tasks' % completed) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 125 | |
| 126 | # |
| 127 | # Class representing a process pool |
| 128 | # |
| 129 | |
| 130 | class Pool(object): |
| 131 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 132 | Class which supports an async version of applying functions to arguments. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 133 | ''' |
| 134 | Process = Process |
| 135 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 136 | def __init__(self, processes=None, initializer=None, initargs=(), |
| 137 | maxtasksperchild=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 138 | self._setup_queues() |
| 139 | self._taskqueue = queue.Queue() |
| 140 | self._cache = {} |
| 141 | self._state = RUN |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 142 | self._maxtasksperchild = maxtasksperchild |
| 143 | self._initializer = initializer |
| 144 | self._initargs = initargs |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 145 | |
| 146 | if processes is None: |
| 147 | try: |
| 148 | processes = cpu_count() |
| 149 | except NotImplementedError: |
| 150 | processes = 1 |
Victor Stinner | 2fae27b | 2011-06-20 17:53:35 +0200 | [diff] [blame] | 151 | if processes < 1: |
| 152 | raise ValueError("Number of processes must be at least 1") |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 153 | |
Benjamin Peterson | f47ed4a | 2009-04-11 20:45:40 +0000 | [diff] [blame] | 154 | if initializer is not None and not hasattr(initializer, '__call__'): |
| 155 | raise TypeError('initializer must be a callable') |
| 156 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 157 | self._processes = processes |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 158 | self._pool = [] |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 159 | self._repopulate_pool() |
| 160 | |
| 161 | self._worker_handler = threading.Thread( |
| 162 | target=Pool._handle_workers, |
| 163 | args=(self, ) |
| 164 | ) |
| 165 | self._worker_handler.daemon = True |
| 166 | self._worker_handler._state = RUN |
| 167 | self._worker_handler.start() |
| 168 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 169 | |
| 170 | self._task_handler = threading.Thread( |
| 171 | target=Pool._handle_tasks, |
| 172 | args=(self._taskqueue, self._quick_put, self._outqueue, self._pool) |
| 173 | ) |
Benjamin Peterson | fae4c62 | 2008-08-18 18:40:08 +0000 | [diff] [blame] | 174 | self._task_handler.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 175 | self._task_handler._state = RUN |
| 176 | self._task_handler.start() |
| 177 | |
| 178 | self._result_handler = threading.Thread( |
| 179 | target=Pool._handle_results, |
| 180 | args=(self._outqueue, self._quick_get, self._cache) |
| 181 | ) |
Benjamin Peterson | fae4c62 | 2008-08-18 18:40:08 +0000 | [diff] [blame] | 182 | self._result_handler.daemon = True |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 183 | self._result_handler._state = RUN |
| 184 | self._result_handler.start() |
| 185 | |
| 186 | self._terminate = Finalize( |
| 187 | self, self._terminate_pool, |
| 188 | args=(self._taskqueue, self._inqueue, self._outqueue, self._pool, |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 189 | self._worker_handler, self._task_handler, |
| 190 | self._result_handler, self._cache), |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 191 | exitpriority=15 |
| 192 | ) |
| 193 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 194 | def _join_exited_workers(self): |
| 195 | """Cleanup after any worker processes which have exited due to reaching |
| 196 | their specified lifetime. Returns True if any workers were cleaned up. |
| 197 | """ |
| 198 | cleaned = False |
| 199 | for i in reversed(range(len(self._pool))): |
| 200 | worker = self._pool[i] |
| 201 | if worker.exitcode is not None: |
| 202 | # worker exited |
| 203 | debug('cleaning up worker %d' % i) |
| 204 | worker.join() |
| 205 | cleaned = True |
| 206 | del self._pool[i] |
| 207 | return cleaned |
| 208 | |
| 209 | def _repopulate_pool(self): |
| 210 | """Bring the number of pool processes up to the specified number, |
| 211 | for use after reaping workers which have exited. |
| 212 | """ |
| 213 | for i in range(self._processes - len(self._pool)): |
| 214 | w = self.Process(target=worker, |
| 215 | args=(self._inqueue, self._outqueue, |
| 216 | self._initializer, |
| 217 | self._initargs, self._maxtasksperchild) |
| 218 | ) |
| 219 | self._pool.append(w) |
| 220 | w.name = w.name.replace('Process', 'PoolWorker') |
| 221 | w.daemon = True |
| 222 | w.start() |
| 223 | debug('added worker') |
| 224 | |
| 225 | def _maintain_pool(self): |
| 226 | """Clean up any exited workers and start replacements for them. |
| 227 | """ |
| 228 | if self._join_exited_workers(): |
| 229 | self._repopulate_pool() |
| 230 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 231 | def _setup_queues(self): |
| 232 | from .queues import SimpleQueue |
| 233 | self._inqueue = SimpleQueue() |
| 234 | self._outqueue = SimpleQueue() |
| 235 | self._quick_put = self._inqueue._writer.send |
| 236 | self._quick_get = self._outqueue._reader.recv |
| 237 | |
| 238 | def apply(self, func, args=(), kwds={}): |
| 239 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 240 | Equivalent of `func(*args, **kwds)`. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 241 | ''' |
| 242 | assert self._state == RUN |
| 243 | return self.apply_async(func, args, kwds).get() |
| 244 | |
| 245 | def map(self, func, iterable, chunksize=None): |
| 246 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 247 | Apply `func` to each element in `iterable`, collecting the results |
| 248 | in a list that is returned. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 249 | ''' |
| 250 | assert self._state == RUN |
| 251 | return self.map_async(func, iterable, chunksize).get() |
| 252 | |
| 253 | def imap(self, func, iterable, chunksize=1): |
| 254 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 255 | Equivalent of `map()` -- can be MUCH slower than `Pool.map()`. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 256 | ''' |
| 257 | assert self._state == RUN |
| 258 | if chunksize == 1: |
| 259 | result = IMapIterator(self._cache) |
| 260 | self._taskqueue.put((((result._job, i, func, (x,), {}) |
| 261 | for i, x in enumerate(iterable)), result._set_length)) |
| 262 | return result |
| 263 | else: |
| 264 | assert chunksize > 1 |
| 265 | task_batches = Pool._get_tasks(func, iterable, chunksize) |
| 266 | result = IMapIterator(self._cache) |
| 267 | self._taskqueue.put((((result._job, i, mapstar, (x,), {}) |
| 268 | for i, x in enumerate(task_batches)), result._set_length)) |
| 269 | return (item for chunk in result for item in chunk) |
| 270 | |
| 271 | def imap_unordered(self, func, iterable, chunksize=1): |
| 272 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 273 | Like `imap()` method but ordering of results is arbitrary. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 274 | ''' |
| 275 | assert self._state == RUN |
| 276 | if chunksize == 1: |
| 277 | result = IMapUnorderedIterator(self._cache) |
| 278 | self._taskqueue.put((((result._job, i, func, (x,), {}) |
| 279 | for i, x in enumerate(iterable)), result._set_length)) |
| 280 | return result |
| 281 | else: |
| 282 | assert chunksize > 1 |
| 283 | task_batches = Pool._get_tasks(func, iterable, chunksize) |
| 284 | result = IMapUnorderedIterator(self._cache) |
| 285 | self._taskqueue.put((((result._job, i, mapstar, (x,), {}) |
| 286 | for i, x in enumerate(task_batches)), result._set_length)) |
| 287 | return (item for chunk in result for item in chunk) |
| 288 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 289 | def apply_async(self, func, args=(), kwds={}, callback=None, |
| 290 | error_callback=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 291 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 292 | Asynchronous version of `apply()` method. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 293 | ''' |
| 294 | assert self._state == RUN |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 295 | result = ApplyResult(self._cache, callback, error_callback) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 296 | self._taskqueue.put(([(result._job, None, func, args, kwds)], None)) |
| 297 | return result |
| 298 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 299 | def map_async(self, func, iterable, chunksize=None, callback=None, |
| 300 | error_callback=None): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 301 | ''' |
Georg Brandl | 9290503 | 2008-11-22 08:51:39 +0000 | [diff] [blame] | 302 | Asynchronous version of `map()` method. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 303 | ''' |
| 304 | assert self._state == RUN |
| 305 | if not hasattr(iterable, '__len__'): |
| 306 | iterable = list(iterable) |
| 307 | |
| 308 | if chunksize is None: |
| 309 | chunksize, extra = divmod(len(iterable), len(self._pool) * 4) |
| 310 | if extra: |
| 311 | chunksize += 1 |
Alexandre Vassalotti | e52e378 | 2009-07-17 09:18:18 +0000 | [diff] [blame] | 312 | if len(iterable) == 0: |
| 313 | chunksize = 0 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 314 | |
| 315 | task_batches = Pool._get_tasks(func, iterable, chunksize) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 316 | result = MapResult(self._cache, chunksize, len(iterable), callback, |
| 317 | error_callback=error_callback) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 318 | self._taskqueue.put((((result._job, i, mapstar, (x,), {}) |
| 319 | for i, x in enumerate(task_batches)), None)) |
| 320 | return result |
| 321 | |
| 322 | @staticmethod |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 323 | def _handle_workers(pool): |
| 324 | while pool._worker_handler._state == RUN and pool._state == RUN: |
| 325 | pool._maintain_pool() |
| 326 | time.sleep(0.1) |
Antoine Pitrou | 81dee6b | 2011-04-11 00:18:59 +0200 | [diff] [blame] | 327 | # send sentinel to stop workers |
| 328 | pool._taskqueue.put(None) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 329 | debug('worker handler exiting') |
| 330 | |
| 331 | @staticmethod |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 332 | def _handle_tasks(taskqueue, put, outqueue, pool): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 333 | thread = threading.current_thread() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 334 | |
| 335 | for taskseq, set_length in iter(taskqueue.get, None): |
| 336 | i = -1 |
| 337 | for i, task in enumerate(taskseq): |
| 338 | if thread._state: |
| 339 | debug('task handler found thread._state != RUN') |
| 340 | break |
| 341 | try: |
| 342 | put(task) |
| 343 | except IOError: |
| 344 | debug('could not put task on queue') |
| 345 | break |
| 346 | else: |
| 347 | if set_length: |
| 348 | debug('doing set_length()') |
| 349 | set_length(i+1) |
| 350 | continue |
| 351 | break |
| 352 | else: |
| 353 | debug('task handler got sentinel') |
| 354 | |
| 355 | |
| 356 | try: |
| 357 | # tell result handler to finish when cache is empty |
| 358 | debug('task handler sending sentinel to result handler') |
| 359 | outqueue.put(None) |
| 360 | |
| 361 | # tell workers there is no more work |
| 362 | debug('task handler sending sentinel to workers') |
| 363 | for p in pool: |
| 364 | put(None) |
| 365 | except IOError: |
| 366 | debug('task handler got IOError when sending sentinels') |
| 367 | |
| 368 | debug('task handler exiting') |
| 369 | |
| 370 | @staticmethod |
| 371 | def _handle_results(outqueue, get, cache): |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 372 | thread = threading.current_thread() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 373 | |
| 374 | while 1: |
| 375 | try: |
| 376 | task = get() |
| 377 | except (IOError, EOFError): |
| 378 | debug('result handler got EOFError/IOError -- exiting') |
| 379 | return |
| 380 | |
| 381 | if thread._state: |
| 382 | assert thread._state == TERMINATE |
| 383 | debug('result handler found thread._state=TERMINATE') |
| 384 | break |
| 385 | |
| 386 | if task is None: |
| 387 | debug('result handler got sentinel') |
| 388 | break |
| 389 | |
| 390 | job, i, obj = task |
| 391 | try: |
| 392 | cache[job]._set(i, obj) |
| 393 | except KeyError: |
| 394 | pass |
| 395 | |
| 396 | while cache and thread._state != TERMINATE: |
| 397 | try: |
| 398 | task = get() |
| 399 | except (IOError, EOFError): |
| 400 | debug('result handler got EOFError/IOError -- exiting') |
| 401 | return |
| 402 | |
| 403 | if task is None: |
| 404 | debug('result handler ignoring extra sentinel') |
| 405 | continue |
| 406 | job, i, obj = task |
| 407 | try: |
| 408 | cache[job]._set(i, obj) |
| 409 | except KeyError: |
| 410 | pass |
| 411 | |
| 412 | if hasattr(outqueue, '_reader'): |
| 413 | debug('ensuring that outqueue is not full') |
| 414 | # If we don't make room available in outqueue then |
| 415 | # attempts to add the sentinel (None) to outqueue may |
| 416 | # block. There is guaranteed to be no more than 2 sentinels. |
| 417 | try: |
| 418 | for i in range(10): |
| 419 | if not outqueue._reader.poll(): |
| 420 | break |
| 421 | get() |
| 422 | except (IOError, EOFError): |
| 423 | pass |
| 424 | |
| 425 | debug('result handler exiting: len(cache)=%s, thread._state=%s', |
| 426 | len(cache), thread._state) |
| 427 | |
| 428 | @staticmethod |
| 429 | def _get_tasks(func, it, size): |
| 430 | it = iter(it) |
| 431 | while 1: |
| 432 | x = tuple(itertools.islice(it, size)) |
| 433 | if not x: |
| 434 | return |
| 435 | yield (func, x) |
| 436 | |
| 437 | def __reduce__(self): |
| 438 | raise NotImplementedError( |
| 439 | 'pool objects cannot be passed between processes or pickled' |
| 440 | ) |
| 441 | |
| 442 | def close(self): |
| 443 | debug('closing pool') |
| 444 | if self._state == RUN: |
| 445 | self._state = CLOSE |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 446 | self._worker_handler._state = CLOSE |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 447 | |
| 448 | def terminate(self): |
| 449 | debug('terminating pool') |
| 450 | self._state = TERMINATE |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 451 | self._worker_handler._state = TERMINATE |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 452 | self._terminate() |
| 453 | |
| 454 | def join(self): |
| 455 | debug('joining pool') |
| 456 | assert self._state in (CLOSE, TERMINATE) |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 457 | self._worker_handler.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 458 | self._task_handler.join() |
| 459 | self._result_handler.join() |
| 460 | for p in self._pool: |
| 461 | p.join() |
| 462 | |
| 463 | @staticmethod |
| 464 | def _help_stuff_finish(inqueue, task_handler, size): |
| 465 | # task_handler may be blocked trying to put items on inqueue |
| 466 | debug('removing tasks from inqueue until task handler finished') |
| 467 | inqueue._rlock.acquire() |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 468 | while task_handler.is_alive() and inqueue._reader.poll(): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 469 | inqueue._reader.recv() |
| 470 | time.sleep(0) |
| 471 | |
| 472 | @classmethod |
| 473 | def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 474 | worker_handler, task_handler, result_handler, cache): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 475 | # this is guaranteed to only be called once |
| 476 | debug('finalizing pool') |
| 477 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 478 | worker_handler._state = TERMINATE |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 479 | task_handler._state = TERMINATE |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 480 | |
| 481 | debug('helping task handler/workers to finish') |
| 482 | cls._help_stuff_finish(inqueue, task_handler, len(pool)) |
| 483 | |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 484 | assert result_handler.is_alive() or len(cache) == 0 |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 485 | |
| 486 | result_handler._state = TERMINATE |
| 487 | outqueue.put(None) # sentinel |
| 488 | |
Antoine Pitrou | 81dee6b | 2011-04-11 00:18:59 +0200 | [diff] [blame] | 489 | # We must wait for the worker handler to exit before terminating |
| 490 | # workers because we don't want workers to be restarted behind our back. |
| 491 | debug('joining worker handler') |
| 492 | worker_handler.join() |
| 493 | |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 494 | # Terminate workers which haven't already finished. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 495 | if pool and hasattr(pool[0], 'terminate'): |
| 496 | debug('terminating workers') |
| 497 | for p in pool: |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 498 | if p.exitcode is None: |
| 499 | p.terminate() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 500 | |
| 501 | debug('joining task handler') |
Antoine Pitrou | 7c3e577 | 2010-04-14 15:44:10 +0000 | [diff] [blame] | 502 | task_handler.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 503 | |
| 504 | debug('joining result handler') |
Antoine Pitrou | bed9a5b | 2011-04-11 00:20:23 +0200 | [diff] [blame] | 505 | result_handler.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 506 | |
| 507 | if pool and hasattr(pool[0], 'terminate'): |
| 508 | debug('joining pool workers') |
| 509 | for p in pool: |
Florent Xicluna | 998171f | 2010-03-08 13:32:17 +0000 | [diff] [blame] | 510 | if p.is_alive(): |
Jesse Noller | 1f0b658 | 2010-01-27 03:36:01 +0000 | [diff] [blame] | 511 | # worker has not yet exited |
Florent Xicluna | 998171f | 2010-03-08 13:32:17 +0000 | [diff] [blame] | 512 | debug('cleaning up worker %d' % p.pid) |
| 513 | p.join() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 514 | |
| 515 | # |
| 516 | # Class whose instances are returned by `Pool.apply_async()` |
| 517 | # |
| 518 | |
| 519 | class ApplyResult(object): |
| 520 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 521 | def __init__(self, cache, callback, error_callback): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 522 | self._cond = threading.Condition(threading.Lock()) |
| 523 | self._job = next(job_counter) |
| 524 | self._cache = cache |
| 525 | self._ready = False |
| 526 | self._callback = callback |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 527 | self._error_callback = error_callback |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 528 | cache[self._job] = self |
| 529 | |
| 530 | def ready(self): |
| 531 | return self._ready |
| 532 | |
| 533 | def successful(self): |
| 534 | assert self._ready |
| 535 | return self._success |
| 536 | |
| 537 | def wait(self, timeout=None): |
| 538 | self._cond.acquire() |
| 539 | try: |
| 540 | if not self._ready: |
| 541 | self._cond.wait(timeout) |
| 542 | finally: |
| 543 | self._cond.release() |
| 544 | |
| 545 | def get(self, timeout=None): |
| 546 | self.wait(timeout) |
| 547 | if not self._ready: |
| 548 | raise TimeoutError |
| 549 | if self._success: |
| 550 | return self._value |
| 551 | else: |
| 552 | raise self._value |
| 553 | |
| 554 | def _set(self, i, obj): |
| 555 | self._success, self._value = obj |
| 556 | if self._callback and self._success: |
| 557 | self._callback(self._value) |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 558 | if self._error_callback and not self._success: |
| 559 | self._error_callback(self._value) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 560 | self._cond.acquire() |
| 561 | try: |
| 562 | self._ready = True |
| 563 | self._cond.notify() |
| 564 | finally: |
| 565 | self._cond.release() |
| 566 | del self._cache[self._job] |
| 567 | |
| 568 | # |
| 569 | # Class whose instances are returned by `Pool.map_async()` |
| 570 | # |
| 571 | |
| 572 | class MapResult(ApplyResult): |
| 573 | |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 574 | def __init__(self, cache, chunksize, length, callback, error_callback): |
| 575 | ApplyResult.__init__(self, cache, callback, |
| 576 | error_callback=error_callback) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 577 | self._success = True |
| 578 | self._value = [None] * length |
| 579 | self._chunksize = chunksize |
| 580 | if chunksize <= 0: |
| 581 | self._number_left = 0 |
| 582 | self._ready = True |
| 583 | else: |
| 584 | self._number_left = length//chunksize + bool(length % chunksize) |
| 585 | |
| 586 | def _set(self, i, success_result): |
| 587 | success, result = success_result |
| 588 | if success: |
| 589 | self._value[i*self._chunksize:(i+1)*self._chunksize] = result |
| 590 | self._number_left -= 1 |
| 591 | if self._number_left == 0: |
| 592 | if self._callback: |
| 593 | self._callback(self._value) |
| 594 | del self._cache[self._job] |
| 595 | self._cond.acquire() |
| 596 | try: |
| 597 | self._ready = True |
| 598 | self._cond.notify() |
| 599 | finally: |
| 600 | self._cond.release() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 601 | else: |
| 602 | self._success = False |
| 603 | self._value = result |
Ask Solem | 2afcbf2 | 2010-11-09 20:55:52 +0000 | [diff] [blame] | 604 | if self._error_callback: |
| 605 | self._error_callback(self._value) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 606 | del self._cache[self._job] |
| 607 | self._cond.acquire() |
| 608 | try: |
| 609 | self._ready = True |
| 610 | self._cond.notify() |
| 611 | finally: |
| 612 | self._cond.release() |
| 613 | |
| 614 | # |
| 615 | # Class whose instances are returned by `Pool.imap()` |
| 616 | # |
| 617 | |
| 618 | class IMapIterator(object): |
| 619 | |
| 620 | def __init__(self, cache): |
| 621 | self._cond = threading.Condition(threading.Lock()) |
| 622 | self._job = next(job_counter) |
| 623 | self._cache = cache |
| 624 | self._items = collections.deque() |
| 625 | self._index = 0 |
| 626 | self._length = None |
| 627 | self._unsorted = {} |
| 628 | cache[self._job] = self |
| 629 | |
| 630 | def __iter__(self): |
| 631 | return self |
| 632 | |
| 633 | def next(self, timeout=None): |
| 634 | self._cond.acquire() |
| 635 | try: |
| 636 | try: |
| 637 | item = self._items.popleft() |
| 638 | except IndexError: |
| 639 | if self._index == self._length: |
| 640 | raise StopIteration |
| 641 | self._cond.wait(timeout) |
| 642 | try: |
| 643 | item = self._items.popleft() |
| 644 | except IndexError: |
| 645 | if self._index == self._length: |
| 646 | raise StopIteration |
| 647 | raise TimeoutError |
| 648 | finally: |
| 649 | self._cond.release() |
| 650 | |
| 651 | success, value = item |
| 652 | if success: |
| 653 | return value |
| 654 | raise value |
| 655 | |
| 656 | __next__ = next # XXX |
| 657 | |
| 658 | def _set(self, i, obj): |
| 659 | self._cond.acquire() |
| 660 | try: |
| 661 | if self._index == i: |
| 662 | self._items.append(obj) |
| 663 | self._index += 1 |
| 664 | while self._index in self._unsorted: |
| 665 | obj = self._unsorted.pop(self._index) |
| 666 | self._items.append(obj) |
| 667 | self._index += 1 |
| 668 | self._cond.notify() |
| 669 | else: |
| 670 | self._unsorted[i] = obj |
| 671 | |
| 672 | if self._index == self._length: |
| 673 | del self._cache[self._job] |
| 674 | finally: |
| 675 | self._cond.release() |
| 676 | |
| 677 | def _set_length(self, length): |
| 678 | self._cond.acquire() |
| 679 | try: |
| 680 | self._length = length |
| 681 | if self._index == self._length: |
| 682 | self._cond.notify() |
| 683 | del self._cache[self._job] |
| 684 | finally: |
| 685 | self._cond.release() |
| 686 | |
| 687 | # |
| 688 | # Class whose instances are returned by `Pool.imap_unordered()` |
| 689 | # |
| 690 | |
| 691 | class IMapUnorderedIterator(IMapIterator): |
| 692 | |
| 693 | def _set(self, i, obj): |
| 694 | self._cond.acquire() |
| 695 | try: |
| 696 | self._items.append(obj) |
| 697 | self._index += 1 |
| 698 | self._cond.notify() |
| 699 | if self._index == self._length: |
| 700 | del self._cache[self._job] |
| 701 | finally: |
| 702 | self._cond.release() |
| 703 | |
| 704 | # |
| 705 | # |
| 706 | # |
| 707 | |
| 708 | class ThreadPool(Pool): |
| 709 | |
| 710 | from .dummy import Process |
| 711 | |
| 712 | def __init__(self, processes=None, initializer=None, initargs=()): |
| 713 | Pool.__init__(self, processes, initializer, initargs) |
| 714 | |
| 715 | def _setup_queues(self): |
| 716 | self._inqueue = queue.Queue() |
| 717 | self._outqueue = queue.Queue() |
| 718 | self._quick_put = self._inqueue.put |
| 719 | self._quick_get = self._outqueue.get |
| 720 | |
| 721 | @staticmethod |
| 722 | def _help_stuff_finish(inqueue, task_handler, size): |
| 723 | # put sentinels at head of inqueue to make workers finish |
| 724 | inqueue.not_empty.acquire() |
| 725 | try: |
| 726 | inqueue.queue.clear() |
| 727 | inqueue.queue.extend([None] * size) |
Benjamin Peterson | 672b803 | 2008-06-11 19:14:14 +0000 | [diff] [blame] | 728 | inqueue.not_empty.notify_all() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 729 | finally: |
| 730 | inqueue.not_empty.release() |