Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 1 | # Copyright 2009 Brian Quinlan. All Rights Reserved. |
| 2 | # Licensed to PSF under a Contributor Agreement. |
| 3 | |
| 4 | """Implements ProcessPoolExecutor. |
| 5 | |
| 6 | The follow diagram and text describe the data-flow through the system: |
| 7 | |
| 8 | |======================= In-process =====================|== Out-of-process ==| |
| 9 | |
| 10 | +----------+ +----------+ +--------+ +-----------+ +---------+ |
| 11 | | | => | Work Ids | => | | => | Call Q | => | | |
| 12 | | | +----------+ | | +-----------+ | | |
| 13 | | | | ... | | | | ... | | | |
| 14 | | | | 6 | | | | 5, call() | | | |
| 15 | | | | 7 | | | | ... | | | |
| 16 | | Process | | ... | | Local | +-----------+ | Process | |
| 17 | | Pool | +----------+ | Worker | | #1..n | |
| 18 | | Executor | | Thread | | | |
| 19 | | | +----------- + | | +-----------+ | | |
| 20 | | | <=> | Work Items | <=> | | <= | Result Q | <= | | |
| 21 | | | +------------+ | | +-----------+ | | |
| 22 | | | | 6: call() | | | | ... | | | |
| 23 | | | | future | | | | 4, result | | | |
| 24 | | | | ... | | | | 3, except | | | |
| 25 | +----------+ +------------+ +--------+ +-----------+ +---------+ |
| 26 | |
| 27 | Executor.submit() called: |
| 28 | - creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict |
| 29 | - adds the id of the _WorkItem to the "Work Ids" queue |
| 30 | |
| 31 | Local worker thread: |
| 32 | - reads work ids from the "Work Ids" queue and looks up the corresponding |
| 33 | WorkItem from the "Work Items" dict: if the work item has been cancelled then |
| 34 | it is simply removed from the dict, otherwise it is repackaged as a |
| 35 | _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q" |
| 36 | until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because |
| 37 | calls placed in the "Call Q" can no longer be cancelled with Future.cancel(). |
| 38 | - reads _ResultItems from "Result Q", updates the future stored in the |
| 39 | "Work Items" dict and deletes the dict entry |
| 40 | |
| 41 | Process #1..n: |
| 42 | - reads _CallItems from "Call Q", executes the calls, and puts the resulting |
Mark Dickinson | 5ee2404 | 2012-10-20 13:16:49 +0100 | [diff] [blame] | 43 | _ResultItems in "Result Q" |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 44 | """ |
| 45 | |
| 46 | __author__ = 'Brian Quinlan (brian@sweetapp.com)' |
| 47 | |
| 48 | import atexit |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 49 | import os |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 50 | from concurrent.futures import _base |
| 51 | import queue |
Richard Oudkerk | 1f2eaa9 | 2013-10-16 17:06:22 +0100 | [diff] [blame] | 52 | from queue import Full |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 53 | import multiprocessing as mp |
Antoine Pitrou | bdb1cf1 | 2012-03-05 19:28:37 +0100 | [diff] [blame] | 54 | from multiprocessing.connection import wait |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 55 | import threading |
| 56 | import weakref |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 57 | from functools import partial |
| 58 | import itertools |
Antoine Pitrou | 1285c9b | 2015-01-17 20:02:14 +0100 | [diff] [blame] | 59 | import traceback |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 60 | |
| 61 | # Workers are created as daemon threads and processes. This is done to allow the |
| 62 | # interpreter to exit when there are still idle processes in a |
| 63 | # ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However, |
| 64 | # allowing workers to die with the interpreter has two undesirable properties: |
Raymond Hettinger | 15f44ab | 2016-08-30 10:47:49 -0700 | [diff] [blame] | 65 | # - The workers would still be running during interpreter shutdown, |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 66 | # meaning that they would fail in unpredictable ways. |
| 67 | # - The workers could be killed while evaluating a work item, which could |
| 68 | # be bad if the callable being evaluated has external side-effects e.g. |
| 69 | # writing to a file. |
| 70 | # |
| 71 | # To work around this problem, an exit handler is installed which tells the |
| 72 | # workers to exit when their work queues are empty and then waits until the |
| 73 | # threads/processes finish. |
| 74 | |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 75 | _threads_queues = weakref.WeakKeyDictionary() |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 76 | _global_shutdown = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 77 | |
| 78 | def _python_exit(): |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 79 | global _global_shutdown |
| 80 | _global_shutdown = True |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 81 | items = list(_threads_queues.items()) |
| 82 | for t, q in items: |
| 83 | q.put(None) |
| 84 | for t, q in items: |
| 85 | t.join() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 86 | |
| 87 | # Controls how many more calls than processes will be queued in the call queue. |
| 88 | # A smaller number will mean that processes spend more time idle waiting for |
| 89 | # work while a larger number will make Future.cancel() succeed less frequently |
| 90 | # (Futures in the call queue cannot be cancelled). |
| 91 | EXTRA_QUEUED_CALLS = 1 |
| 92 | |
Antoine Pitrou | 1285c9b | 2015-01-17 20:02:14 +0100 | [diff] [blame] | 93 | # Hack to embed stringification of remote traceback in local traceback |
| 94 | |
| 95 | class _RemoteTraceback(Exception): |
| 96 | def __init__(self, tb): |
| 97 | self.tb = tb |
| 98 | def __str__(self): |
| 99 | return self.tb |
| 100 | |
| 101 | class _ExceptionWithTraceback: |
| 102 | def __init__(self, exc, tb): |
| 103 | tb = traceback.format_exception(type(exc), exc, tb) |
| 104 | tb = ''.join(tb) |
| 105 | self.exc = exc |
| 106 | self.tb = '\n"""\n%s"""' % tb |
| 107 | def __reduce__(self): |
| 108 | return _rebuild_exc, (self.exc, self.tb) |
| 109 | |
| 110 | def _rebuild_exc(exc, tb): |
| 111 | exc.__cause__ = _RemoteTraceback(tb) |
| 112 | return exc |
| 113 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 114 | class _WorkItem(object): |
| 115 | def __init__(self, future, fn, args, kwargs): |
| 116 | self.future = future |
| 117 | self.fn = fn |
| 118 | self.args = args |
| 119 | self.kwargs = kwargs |
| 120 | |
| 121 | class _ResultItem(object): |
| 122 | def __init__(self, work_id, exception=None, result=None): |
| 123 | self.work_id = work_id |
| 124 | self.exception = exception |
| 125 | self.result = result |
| 126 | |
| 127 | class _CallItem(object): |
| 128 | def __init__(self, work_id, fn, args, kwargs): |
| 129 | self.work_id = work_id |
| 130 | self.fn = fn |
| 131 | self.args = args |
| 132 | self.kwargs = kwargs |
| 133 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 134 | |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 135 | def _get_chunks(*iterables, chunksize): |
| 136 | """ Iterates over zip()ed iterables in chunks. """ |
| 137 | it = zip(*iterables) |
| 138 | while True: |
| 139 | chunk = tuple(itertools.islice(it, chunksize)) |
| 140 | if not chunk: |
| 141 | return |
| 142 | yield chunk |
| 143 | |
| 144 | def _process_chunk(fn, chunk): |
| 145 | """ Processes a chunk of an iterable passed to map. |
| 146 | |
| 147 | Runs the function passed to map() on a chunk of the |
| 148 | iterable passed to map. |
| 149 | |
| 150 | This function is run in a separate process. |
| 151 | |
| 152 | """ |
| 153 | return [fn(*args) for args in chunk] |
| 154 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 155 | def _process_worker(call_queue, result_queue, initializer, initargs): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 156 | """Evaluates calls from call_queue and places the results in result_queue. |
| 157 | |
Georg Brandl | fb1720b | 2010-12-09 18:08:43 +0000 | [diff] [blame] | 158 | This worker is run in a separate process. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 159 | |
| 160 | Args: |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 161 | call_queue: A ctx.Queue of _CallItems that will be read and |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 162 | evaluated by the worker. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 163 | result_queue: A ctx.Queue of _ResultItems that will written |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 164 | to by the worker. |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 165 | initializer: A callable initializer, or None |
| 166 | initargs: A tuple of args for the initializer |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 167 | """ |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 168 | if initializer is not None: |
| 169 | try: |
| 170 | initializer(*initargs) |
| 171 | except BaseException: |
| 172 | _base.LOGGER.critical('Exception in initializer:', exc_info=True) |
| 173 | # The parent will notice that the process stopped and |
| 174 | # mark the pool broken |
| 175 | return |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 176 | while True: |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 177 | call_item = call_queue.get(block=True) |
| 178 | if call_item is None: |
| 179 | # Wake up queue management thread |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 180 | result_queue.put(os.getpid()) |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 181 | return |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 182 | try: |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 183 | r = call_item.fn(*call_item.args, **call_item.kwargs) |
| 184 | except BaseException as e: |
Antoine Pitrou | 1285c9b | 2015-01-17 20:02:14 +0100 | [diff] [blame] | 185 | exc = _ExceptionWithTraceback(e, e.__traceback__) |
| 186 | result_queue.put(_ResultItem(call_item.work_id, exception=exc)) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 187 | else: |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 188 | result_queue.put(_ResultItem(call_item.work_id, |
| 189 | result=r)) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 190 | |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 191 | # Liberate the resource as soon as possible, to avoid holding onto |
| 192 | # open files or shared memory that is not needed anymore |
| 193 | del call_item |
| 194 | |
| 195 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 196 | def _add_call_item_to_queue(pending_work_items, |
| 197 | work_ids, |
| 198 | call_queue): |
| 199 | """Fills call_queue with _WorkItems from pending_work_items. |
| 200 | |
| 201 | This function never blocks. |
| 202 | |
| 203 | Args: |
| 204 | pending_work_items: A dict mapping work ids to _WorkItems e.g. |
| 205 | {5: <_WorkItem...>, 6: <_WorkItem...>, ...} |
| 206 | work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids |
| 207 | are consumed and the corresponding _WorkItems from |
| 208 | pending_work_items are transformed into _CallItems and put in |
| 209 | call_queue. |
| 210 | call_queue: A multiprocessing.Queue that will be filled with _CallItems |
| 211 | derived from _WorkItems. |
| 212 | """ |
| 213 | while True: |
| 214 | if call_queue.full(): |
| 215 | return |
| 216 | try: |
| 217 | work_id = work_ids.get(block=False) |
| 218 | except queue.Empty: |
| 219 | return |
| 220 | else: |
| 221 | work_item = pending_work_items[work_id] |
| 222 | |
| 223 | if work_item.future.set_running_or_notify_cancel(): |
| 224 | call_queue.put(_CallItem(work_id, |
| 225 | work_item.fn, |
| 226 | work_item.args, |
| 227 | work_item.kwargs), |
| 228 | block=True) |
| 229 | else: |
| 230 | del pending_work_items[work_id] |
| 231 | continue |
| 232 | |
Antoine Pitrou | b87a56a | 2011-05-03 16:34:42 +0200 | [diff] [blame] | 233 | def _queue_management_worker(executor_reference, |
| 234 | processes, |
| 235 | pending_work_items, |
| 236 | work_ids_queue, |
| 237 | call_queue, |
| 238 | result_queue): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 239 | """Manages the communication between this process and the worker processes. |
| 240 | |
| 241 | This function is run in a local thread. |
| 242 | |
| 243 | Args: |
| 244 | executor_reference: A weakref.ref to the ProcessPoolExecutor that owns |
| 245 | this thread. Used to determine if the ProcessPoolExecutor has been |
| 246 | garbage collected and that this function can exit. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 247 | process: A list of the ctx.Process instances used as |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 248 | workers. |
| 249 | pending_work_items: A dict mapping work ids to _WorkItems e.g. |
| 250 | {5: <_WorkItem...>, 6: <_WorkItem...>, ...} |
| 251 | work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]). |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 252 | call_queue: A ctx.Queue that will be filled with _CallItems |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 253 | derived from _WorkItems for processing by the process workers. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 254 | result_queue: A ctx.SimpleQueue of _ResultItems generated by the |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 255 | process workers. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 256 | """ |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 257 | executor = None |
| 258 | |
| 259 | def shutting_down(): |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 260 | return (_global_shutdown or executor is None |
| 261 | or executor._shutdown_thread) |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 262 | |
| 263 | def shutdown_worker(): |
| 264 | # This is an upper bound |
| 265 | nb_children_alive = sum(p.is_alive() for p in processes.values()) |
| 266 | for i in range(0, nb_children_alive): |
Antoine Pitrou | 1c405b3 | 2011-07-03 13:17:06 +0200 | [diff] [blame] | 267 | call_queue.put_nowait(None) |
Antoine Pitrou | dc19c24 | 2011-07-16 01:51:58 +0200 | [diff] [blame] | 268 | # Release the queue's resources as soon as possible. |
| 269 | call_queue.close() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 270 | # If .join() is not called on the created processes then |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 271 | # some ctx.Queue methods may deadlock on Mac OS X. |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 272 | for p in processes.values(): |
| 273 | p.join() |
| 274 | |
Antoine Pitrou | bdb1cf1 | 2012-03-05 19:28:37 +0100 | [diff] [blame] | 275 | reader = result_queue._reader |
| 276 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 277 | while True: |
| 278 | _add_call_item_to_queue(pending_work_items, |
| 279 | work_ids_queue, |
| 280 | call_queue) |
| 281 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 282 | sentinels = [p.sentinel for p in processes.values()] |
| 283 | assert sentinels |
Antoine Pitrou | bdb1cf1 | 2012-03-05 19:28:37 +0100 | [diff] [blame] | 284 | ready = wait([reader] + sentinels) |
| 285 | if reader in ready: |
| 286 | result_item = reader.recv() |
| 287 | else: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 288 | # Mark the process pool broken so that submits fail right now. |
| 289 | executor = executor_reference() |
| 290 | if executor is not None: |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 291 | executor._broken = ('A child process terminated ' |
| 292 | 'abruptly, the process pool is not ' |
| 293 | 'usable anymore') |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 294 | executor._shutdown_thread = True |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 295 | executor = None |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 296 | # All futures in flight must be marked failed |
| 297 | for work_id, work_item in pending_work_items.items(): |
| 298 | work_item.future.set_exception( |
| 299 | BrokenProcessPool( |
| 300 | "A process in the process pool was " |
| 301 | "terminated abruptly while the future was " |
| 302 | "running or pending." |
| 303 | )) |
Andrew Svetlov | 6b97374 | 2012-11-03 15:36:01 +0200 | [diff] [blame] | 304 | # Delete references to object. See issue16284 |
| 305 | del work_item |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 306 | pending_work_items.clear() |
| 307 | # Terminate remaining workers forcibly: the queues or their |
| 308 | # locks may be in a dirty state and block forever. |
| 309 | for p in processes.values(): |
| 310 | p.terminate() |
Antoine Pitrou | dc19c24 | 2011-07-16 01:51:58 +0200 | [diff] [blame] | 311 | shutdown_worker() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 312 | return |
| 313 | if isinstance(result_item, int): |
| 314 | # Clean shutdown of a worker using its PID |
| 315 | # (avoids marking the executor broken) |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 316 | assert shutting_down() |
Antoine Pitrou | d06a065 | 2011-07-16 01:13:34 +0200 | [diff] [blame] | 317 | p = processes.pop(result_item) |
| 318 | p.join() |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 319 | if not processes: |
| 320 | shutdown_worker() |
| 321 | return |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 322 | elif result_item is not None: |
| 323 | work_item = pending_work_items.pop(result_item.work_id, None) |
| 324 | # work_item can be None if another process terminated (see above) |
| 325 | if work_item is not None: |
| 326 | if result_item.exception: |
| 327 | work_item.future.set_exception(result_item.exception) |
| 328 | else: |
| 329 | work_item.future.set_result(result_item.result) |
Andrew Svetlov | 6b97374 | 2012-11-03 15:36:01 +0200 | [diff] [blame] | 330 | # Delete references to object. See issue16284 |
| 331 | del work_item |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 332 | # Check whether we should start shutting down. |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 333 | executor = executor_reference() |
| 334 | # No more work items can be added if: |
| 335 | # - The interpreter is shutting down OR |
| 336 | # - The executor that owns this worker has been collected OR |
| 337 | # - The executor that owns this worker has been shutdown. |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 338 | if shutting_down(): |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 339 | try: |
Antoine Pitrou | 1c405b3 | 2011-07-03 13:17:06 +0200 | [diff] [blame] | 340 | # Since no new work items can be added, it is safe to shutdown |
| 341 | # this thread if there are no pending work items. |
| 342 | if not pending_work_items: |
| 343 | shutdown_worker() |
| 344 | return |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 345 | except Full: |
| 346 | # This is not a problem: we will eventually be woken up (in |
Antoine Pitrou | 1c405b3 | 2011-07-03 13:17:06 +0200 | [diff] [blame] | 347 | # result_queue.get()) and be able to send a sentinel again. |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 348 | pass |
| 349 | executor = None |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 350 | |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 351 | _system_limits_checked = False |
| 352 | _system_limited = None |
| 353 | def _check_system_limits(): |
| 354 | global _system_limits_checked, _system_limited |
| 355 | if _system_limits_checked: |
| 356 | if _system_limited: |
| 357 | raise NotImplementedError(_system_limited) |
| 358 | _system_limits_checked = True |
| 359 | try: |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 360 | nsems_max = os.sysconf("SC_SEM_NSEMS_MAX") |
| 361 | except (AttributeError, ValueError): |
| 362 | # sysconf not available or setting not available |
| 363 | return |
| 364 | if nsems_max == -1: |
Ezio Melotti | b5bc353 | 2013-08-17 16:11:40 +0300 | [diff] [blame] | 365 | # indetermined limit, assume that limit is determined |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 366 | # by available memory only |
| 367 | return |
| 368 | if nsems_max >= 256: |
| 369 | # minimum number of semaphores available |
| 370 | # according to POSIX |
| 371 | return |
| 372 | _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max |
| 373 | raise NotImplementedError(_system_limited) |
| 374 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 375 | |
Grzegorz Grzywacz | 97e1b1c | 2017-09-01 18:54:00 +0200 | [diff] [blame] | 376 | def _chain_from_iterable_of_lists(iterable): |
| 377 | """ |
| 378 | Specialized implementation of itertools.chain.from_iterable. |
| 379 | Each item in *iterable* should be a list. This function is |
| 380 | careful not to keep references to yielded objects. |
| 381 | """ |
| 382 | for element in iterable: |
| 383 | element.reverse() |
| 384 | while element: |
| 385 | yield element.pop() |
| 386 | |
| 387 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 388 | class BrokenProcessPool(_base.BrokenExecutor): |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 389 | """ |
| 390 | Raised when a process in a ProcessPoolExecutor terminated abruptly |
| 391 | while a future was in the running state. |
| 392 | """ |
| 393 | |
| 394 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 395 | class ProcessPoolExecutor(_base.Executor): |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 396 | def __init__(self, max_workers=None, mp_context=None, |
| 397 | initializer=None, initargs=()): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 398 | """Initializes a new ProcessPoolExecutor instance. |
| 399 | |
| 400 | Args: |
| 401 | max_workers: The maximum number of processes that can be used to |
| 402 | execute the given calls. If None or not given then as many |
| 403 | worker processes will be created as the machine has processors. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 404 | mp_context: A multiprocessing context to launch the workers. This |
| 405 | object should provide SimpleQueue, Queue and Process. |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 406 | initializer: An callable used to initialize worker processes. |
| 407 | initargs: A tuple of arguments to pass to the initializer. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 408 | """ |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 409 | _check_system_limits() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 410 | |
| 411 | if max_workers is None: |
Charles-François Natali | 37cfb0a | 2013-06-28 19:25:45 +0200 | [diff] [blame] | 412 | self._max_workers = os.cpu_count() or 1 |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 413 | else: |
Brian Quinlan | 20efceb | 2014-05-17 13:51:10 -0700 | [diff] [blame] | 414 | if max_workers <= 0: |
| 415 | raise ValueError("max_workers must be greater than 0") |
| 416 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 417 | self._max_workers = max_workers |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 418 | if mp_context is None: |
| 419 | mp_context = mp.get_context() |
| 420 | self._mp_context = mp_context |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 421 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 422 | if initializer is not None and not callable(initializer): |
| 423 | raise TypeError("initializer must be a callable") |
| 424 | self._initializer = initializer |
| 425 | self._initargs = initargs |
| 426 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 427 | # Make the call queue slightly larger than the number of processes to |
| 428 | # prevent the worker processes from idling. But don't make it too big |
| 429 | # because futures in the call queue cannot be cancelled. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 430 | queue_size = self._max_workers + EXTRA_QUEUED_CALLS |
| 431 | self._call_queue = mp_context.Queue(queue_size) |
Antoine Pitrou | dc19c24 | 2011-07-16 01:51:58 +0200 | [diff] [blame] | 432 | # Killed worker processes can produce spurious "broken pipe" |
| 433 | # tracebacks in the queue's own worker thread. But we detect killed |
| 434 | # processes anyway, so silence the tracebacks. |
| 435 | self._call_queue._ignore_epipe = True |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 436 | self._result_queue = mp_context.SimpleQueue() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 437 | self._work_ids = queue.Queue() |
| 438 | self._queue_management_thread = None |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 439 | # Map of pids to processes |
| 440 | self._processes = {} |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 441 | |
| 442 | # Shutdown is a two-step process. |
| 443 | self._shutdown_thread = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 444 | self._shutdown_lock = threading.Lock() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 445 | self._broken = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 446 | self._queue_count = 0 |
| 447 | self._pending_work_items = {} |
| 448 | |
| 449 | def _start_queue_management_thread(self): |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 450 | # When the executor gets lost, the weakref callback will wake up |
| 451 | # the queue management thread. |
| 452 | def weakref_cb(_, q=self._result_queue): |
| 453 | q.put(None) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 454 | if self._queue_management_thread is None: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 455 | # Start the processes so that their sentinels are known. |
| 456 | self._adjust_process_count() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 457 | self._queue_management_thread = threading.Thread( |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 458 | target=_queue_management_worker, |
| 459 | args=(weakref.ref(self, weakref_cb), |
| 460 | self._processes, |
| 461 | self._pending_work_items, |
| 462 | self._work_ids, |
| 463 | self._call_queue, |
| 464 | self._result_queue)) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 465 | self._queue_management_thread.daemon = True |
| 466 | self._queue_management_thread.start() |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 467 | _threads_queues[self._queue_management_thread] = self._result_queue |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 468 | |
| 469 | def _adjust_process_count(self): |
| 470 | for _ in range(len(self._processes), self._max_workers): |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 471 | p = self._mp_context.Process( |
| 472 | target=_process_worker, |
| 473 | args=(self._call_queue, |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 474 | self._result_queue, |
| 475 | self._initializer, |
| 476 | self._initargs)) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 477 | p.start() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 478 | self._processes[p.pid] = p |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 479 | |
| 480 | def submit(self, fn, *args, **kwargs): |
| 481 | with self._shutdown_lock: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 482 | if self._broken: |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 483 | raise BrokenProcessPool(self._broken) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 484 | if self._shutdown_thread: |
| 485 | raise RuntimeError('cannot schedule new futures after shutdown') |
| 486 | |
| 487 | f = _base.Future() |
| 488 | w = _WorkItem(f, fn, args, kwargs) |
| 489 | |
| 490 | self._pending_work_items[self._queue_count] = w |
| 491 | self._work_ids.put(self._queue_count) |
| 492 | self._queue_count += 1 |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 493 | # Wake up queue management thread |
| 494 | self._result_queue.put(None) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 495 | |
| 496 | self._start_queue_management_thread() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 497 | return f |
| 498 | submit.__doc__ = _base.Executor.submit.__doc__ |
| 499 | |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 500 | def map(self, fn, *iterables, timeout=None, chunksize=1): |
Martin Panter | d2ad571 | 2015-11-02 04:20:33 +0000 | [diff] [blame] | 501 | """Returns an iterator equivalent to map(fn, iter). |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 502 | |
| 503 | Args: |
| 504 | fn: A callable that will take as many arguments as there are |
| 505 | passed iterables. |
| 506 | timeout: The maximum number of seconds to wait. If None, then there |
| 507 | is no limit on the wait time. |
| 508 | chunksize: If greater than one, the iterables will be chopped into |
| 509 | chunks of size chunksize and submitted to the process pool. |
| 510 | If set to one, the items in the list will be sent one at a time. |
| 511 | |
| 512 | Returns: |
| 513 | An iterator equivalent to: map(func, *iterables) but the calls may |
| 514 | be evaluated out-of-order. |
| 515 | |
| 516 | Raises: |
| 517 | TimeoutError: If the entire result iterator could not be generated |
| 518 | before the given timeout. |
| 519 | Exception: If fn(*args) raises for any values. |
| 520 | """ |
| 521 | if chunksize < 1: |
| 522 | raise ValueError("chunksize must be >= 1.") |
| 523 | |
| 524 | results = super().map(partial(_process_chunk, fn), |
| 525 | _get_chunks(*iterables, chunksize=chunksize), |
| 526 | timeout=timeout) |
Grzegorz Grzywacz | 97e1b1c | 2017-09-01 18:54:00 +0200 | [diff] [blame] | 527 | return _chain_from_iterable_of_lists(results) |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 528 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 529 | def shutdown(self, wait=True): |
| 530 | with self._shutdown_lock: |
| 531 | self._shutdown_thread = True |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 532 | if self._queue_management_thread: |
| 533 | # Wake up queue management thread |
| 534 | self._result_queue.put(None) |
| 535 | if wait: |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 536 | self._queue_management_thread.join() |
Ezio Melotti | b5bc353 | 2013-08-17 16:11:40 +0300 | [diff] [blame] | 537 | # To reduce the risk of opening too many files, remove references to |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 538 | # objects that use file descriptors. |
| 539 | self._queue_management_thread = None |
Victor Stinner | b713adf | 2017-09-02 00:25:11 +0200 | [diff] [blame] | 540 | if self._call_queue is not None: |
| 541 | self._call_queue.close() |
| 542 | if wait: |
| 543 | self._call_queue.join_thread() |
| 544 | self._call_queue = None |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 545 | self._result_queue = None |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 546 | self._processes = None |
| 547 | shutdown.__doc__ = _base.Executor.shutdown.__doc__ |
| 548 | |
| 549 | atexit.register(_python_exit) |