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 | |
Thomas Grainger | f938d8b | 2019-04-12 17:17:17 +0100 | [diff] [blame] | 6 | The following diagram and text describe the data-flow through the system: |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 7 | |
| 8 | |======================= In-process =====================|== Out-of-process ==| |
| 9 | |
| 10 | +----------+ +----------+ +--------+ +-----------+ +---------+ |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 11 | | | => | Work Ids | | | | Call Q | | Process | |
| 12 | | | +----------+ | | +-----------+ | Pool | |
| 13 | | | | ... | | | | ... | +---------+ |
| 14 | | | | 6 | => | | => | 5, call() | => | | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 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 |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 52 | import multiprocessing as mp |
Brian Quinlan | f7bda5c | 2019-05-07 13:31:11 -0400 | [diff] [blame] | 53 | import multiprocessing.connection |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 54 | from multiprocessing.queues import Queue |
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 |
Brian Quinlan | 3988986 | 2019-05-08 14:04:53 -0400 | [diff] [blame] | 59 | import sys |
Antoine Pitrou | 1285c9b | 2015-01-17 20:02:14 +0100 | [diff] [blame] | 60 | import traceback |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 61 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 62 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 63 | _threads_wakeups = weakref.WeakKeyDictionary() |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 64 | _global_shutdown = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 65 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 66 | |
| 67 | class _ThreadWakeup: |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 68 | def __init__(self): |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 69 | self._closed = False |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 70 | self._reader, self._writer = mp.Pipe(duplex=False) |
| 71 | |
Thomas Moreau | 095ee41 | 2018-03-12 18:18:41 +0100 | [diff] [blame] | 72 | def close(self): |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 73 | if not self._closed: |
| 74 | self._closed = True |
| 75 | self._writer.close() |
| 76 | self._reader.close() |
Thomas Moreau | 095ee41 | 2018-03-12 18:18:41 +0100 | [diff] [blame] | 77 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 78 | def wakeup(self): |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 79 | if not self._closed: |
| 80 | self._writer.send_bytes(b"") |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 81 | |
| 82 | def clear(self): |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 83 | if not self._closed: |
| 84 | while self._reader.poll(): |
| 85 | self._reader.recv_bytes() |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 86 | |
| 87 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 88 | def _python_exit(): |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 89 | global _global_shutdown |
| 90 | _global_shutdown = True |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 91 | items = list(_threads_wakeups.items()) |
| 92 | for _, thread_wakeup in items: |
| 93 | thread_wakeup.wakeup() |
| 94 | for t, _ in items: |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 95 | t.join() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 96 | |
Kyle Stanley | b61b818 | 2020-03-27 15:31:22 -0400 | [diff] [blame^] | 97 | # Register for `_python_exit()` to be called just before joining all |
| 98 | # non-daemon threads. This is used instead of `atexit.register()` for |
| 99 | # compatibility with subinterpreters, which no longer support daemon threads. |
| 100 | # See bpo-39812 for context. |
| 101 | threading._register_atexit(_python_exit) |
| 102 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 103 | # Controls how many more calls than processes will be queued in the call queue. |
| 104 | # A smaller number will mean that processes spend more time idle waiting for |
| 105 | # work while a larger number will make Future.cancel() succeed less frequently |
| 106 | # (Futures in the call queue cannot be cancelled). |
| 107 | EXTRA_QUEUED_CALLS = 1 |
| 108 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 109 | |
Brian Quinlan | 3988986 | 2019-05-08 14:04:53 -0400 | [diff] [blame] | 110 | # On Windows, WaitForMultipleObjects is used to wait for processes to finish. |
| 111 | # It can wait on, at most, 63 objects. There is an overhead of two objects: |
| 112 | # - the result queue reader |
| 113 | # - the thread wakeup reader |
| 114 | _MAX_WINDOWS_WORKERS = 63 - 2 |
| 115 | |
Antoine Pitrou | 1285c9b | 2015-01-17 20:02:14 +0100 | [diff] [blame] | 116 | # Hack to embed stringification of remote traceback in local traceback |
| 117 | |
| 118 | class _RemoteTraceback(Exception): |
| 119 | def __init__(self, tb): |
| 120 | self.tb = tb |
| 121 | def __str__(self): |
| 122 | return self.tb |
| 123 | |
| 124 | class _ExceptionWithTraceback: |
| 125 | def __init__(self, exc, tb): |
| 126 | tb = traceback.format_exception(type(exc), exc, tb) |
| 127 | tb = ''.join(tb) |
| 128 | self.exc = exc |
| 129 | self.tb = '\n"""\n%s"""' % tb |
| 130 | def __reduce__(self): |
| 131 | return _rebuild_exc, (self.exc, self.tb) |
| 132 | |
| 133 | def _rebuild_exc(exc, tb): |
| 134 | exc.__cause__ = _RemoteTraceback(tb) |
| 135 | return exc |
| 136 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 137 | class _WorkItem(object): |
| 138 | def __init__(self, future, fn, args, kwargs): |
| 139 | self.future = future |
| 140 | self.fn = fn |
| 141 | self.args = args |
| 142 | self.kwargs = kwargs |
| 143 | |
| 144 | class _ResultItem(object): |
| 145 | def __init__(self, work_id, exception=None, result=None): |
| 146 | self.work_id = work_id |
| 147 | self.exception = exception |
| 148 | self.result = result |
| 149 | |
| 150 | class _CallItem(object): |
| 151 | def __init__(self, work_id, fn, args, kwargs): |
| 152 | self.work_id = work_id |
| 153 | self.fn = fn |
| 154 | self.args = args |
| 155 | self.kwargs = kwargs |
| 156 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 157 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 158 | class _SafeQueue(Queue): |
| 159 | """Safe Queue set exception to the future object linked to a job""" |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 160 | def __init__(self, max_size=0, *, ctx, pending_work_items, thread_wakeup): |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 161 | self.pending_work_items = pending_work_items |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 162 | self.thread_wakeup = thread_wakeup |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 163 | super().__init__(max_size, ctx=ctx) |
| 164 | |
| 165 | def _on_queue_feeder_error(self, e, obj): |
| 166 | if isinstance(obj, _CallItem): |
| 167 | tb = traceback.format_exception(type(e), e, e.__traceback__) |
| 168 | e.__cause__ = _RemoteTraceback('\n"""\n{}"""'.format(''.join(tb))) |
| 169 | work_item = self.pending_work_items.pop(obj.work_id, None) |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 170 | self.thread_wakeup.wakeup() |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 171 | # work_item can be None if another process terminated. In this |
| 172 | # case, the executor_manager_thread fails all work_items |
| 173 | # with BrokenProcessPool |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 174 | if work_item is not None: |
| 175 | work_item.future.set_exception(e) |
| 176 | else: |
| 177 | super()._on_queue_feeder_error(e, obj) |
| 178 | |
| 179 | |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 180 | def _get_chunks(*iterables, chunksize): |
| 181 | """ Iterates over zip()ed iterables in chunks. """ |
| 182 | it = zip(*iterables) |
| 183 | while True: |
| 184 | chunk = tuple(itertools.islice(it, chunksize)) |
| 185 | if not chunk: |
| 186 | return |
| 187 | yield chunk |
| 188 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 189 | |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 190 | def _process_chunk(fn, chunk): |
| 191 | """ Processes a chunk of an iterable passed to map. |
| 192 | |
| 193 | Runs the function passed to map() on a chunk of the |
| 194 | iterable passed to map. |
| 195 | |
| 196 | This function is run in a separate process. |
| 197 | |
| 198 | """ |
| 199 | return [fn(*args) for args in chunk] |
| 200 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 201 | |
| 202 | def _sendback_result(result_queue, work_id, result=None, exception=None): |
| 203 | """Safely send back the given result or exception""" |
| 204 | try: |
| 205 | result_queue.put(_ResultItem(work_id, result=result, |
| 206 | exception=exception)) |
| 207 | except BaseException as e: |
| 208 | exc = _ExceptionWithTraceback(e, e.__traceback__) |
| 209 | result_queue.put(_ResultItem(work_id, exception=exc)) |
| 210 | |
| 211 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 212 | def _process_worker(call_queue, result_queue, initializer, initargs): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 213 | """Evaluates calls from call_queue and places the results in result_queue. |
| 214 | |
Georg Brandl | fb1720b | 2010-12-09 18:08:43 +0000 | [diff] [blame] | 215 | This worker is run in a separate process. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 216 | |
| 217 | Args: |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 218 | call_queue: A ctx.Queue of _CallItems that will be read and |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 219 | evaluated by the worker. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 220 | result_queue: A ctx.Queue of _ResultItems that will written |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 221 | to by the worker. |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 222 | initializer: A callable initializer, or None |
| 223 | initargs: A tuple of args for the initializer |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 224 | """ |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 225 | if initializer is not None: |
| 226 | try: |
| 227 | initializer(*initargs) |
| 228 | except BaseException: |
| 229 | _base.LOGGER.critical('Exception in initializer:', exc_info=True) |
| 230 | # The parent will notice that the process stopped and |
| 231 | # mark the pool broken |
| 232 | return |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 233 | while True: |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 234 | call_item = call_queue.get(block=True) |
| 235 | if call_item is None: |
| 236 | # Wake up queue management thread |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 237 | result_queue.put(os.getpid()) |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 238 | return |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 239 | try: |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 240 | r = call_item.fn(*call_item.args, **call_item.kwargs) |
| 241 | except BaseException as e: |
Antoine Pitrou | 1285c9b | 2015-01-17 20:02:14 +0100 | [diff] [blame] | 242 | exc = _ExceptionWithTraceback(e, e.__traceback__) |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 243 | _sendback_result(result_queue, call_item.work_id, exception=exc) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 244 | else: |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 245 | _sendback_result(result_queue, call_item.work_id, result=r) |
Dave Chevell | 962bdea | 2019-03-17 09:28:51 +1100 | [diff] [blame] | 246 | del r |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 247 | |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 248 | # Liberate the resource as soon as possible, to avoid holding onto |
| 249 | # open files or shared memory that is not needed anymore |
| 250 | del call_item |
| 251 | |
| 252 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 253 | class _ExecutorManagerThread(threading.Thread): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 254 | """Manages the communication between this process and the worker processes. |
| 255 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 256 | The manager is run in a local thread. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 257 | |
| 258 | Args: |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 259 | executor: A reference to the ProcessPoolExecutor that owns |
| 260 | this thread. A weakref will be own by the manager as well as |
| 261 | references to internal objects used to introspect the state of |
| 262 | the executor. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 263 | """ |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 264 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 265 | def __init__(self, executor): |
| 266 | # Store references to necessary internals of the executor. |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 267 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 268 | # A _ThreadWakeup to allow waking up the queue_manager_thread from the |
| 269 | # main Thread and avoid deadlocks caused by permanently locked queues. |
| 270 | self.thread_wakeup = executor._executor_manager_thread_wakeup |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 271 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 272 | # A weakref.ref to the ProcessPoolExecutor that owns this thread. Used |
| 273 | # to determine if the ProcessPoolExecutor has been garbage collected |
| 274 | # and that the manager can exit. |
| 275 | # When the executor gets garbage collected, the weakref callback |
| 276 | # will wake up the queue management thread so that it can terminate |
| 277 | # if there is no pending work item. |
| 278 | def weakref_cb(_, thread_wakeup=self.thread_wakeup): |
| 279 | mp.util.debug('Executor collected: triggering callback for' |
| 280 | ' QueueManager wakeup') |
| 281 | thread_wakeup.wakeup() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 282 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 283 | self.executor_reference = weakref.ref(executor, weakref_cb) |
Antoine Pitrou | bdb1cf1 | 2012-03-05 19:28:37 +0100 | [diff] [blame] | 284 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 285 | # A list of the ctx.Process instances used as workers. |
| 286 | self.processes = executor._processes |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 287 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 288 | # A ctx.Queue that will be filled with _CallItems derived from |
| 289 | # _WorkItems for processing by the process workers. |
| 290 | self.call_queue = executor._call_queue |
| 291 | |
| 292 | # A ctx.SimpleQueue of _ResultItems generated by the process workers. |
| 293 | self.result_queue = executor._result_queue |
| 294 | |
| 295 | # A queue.Queue of work ids e.g. Queue([5, 6, ...]). |
| 296 | self.work_ids_queue = executor._work_ids |
| 297 | |
| 298 | # A dict mapping work ids to _WorkItems e.g. |
| 299 | # {5: <_WorkItem...>, 6: <_WorkItem...>, ...} |
| 300 | self.pending_work_items = executor._pending_work_items |
| 301 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 302 | super().__init__() |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 303 | |
| 304 | def run(self): |
| 305 | # Main loop for the executor manager thread. |
| 306 | |
| 307 | while True: |
| 308 | self.add_call_item_to_queue() |
| 309 | |
| 310 | result_item, is_broken, cause = self.wait_result_broken_or_wakeup() |
| 311 | |
| 312 | if is_broken: |
| 313 | self.terminate_broken(cause) |
| 314 | return |
| 315 | if result_item is not None: |
| 316 | self.process_result_item(result_item) |
| 317 | # Delete reference to result_item to avoid keeping references |
| 318 | # while waiting on new results. |
| 319 | del result_item |
| 320 | |
| 321 | if self.is_shutting_down(): |
| 322 | self.flag_executor_shutting_down() |
| 323 | |
| 324 | # Since no new work items can be added, it is safe to shutdown |
| 325 | # this thread if there are no pending work items. |
| 326 | if not self.pending_work_items: |
| 327 | self.join_executor_internals() |
| 328 | return |
| 329 | |
| 330 | def add_call_item_to_queue(self): |
| 331 | # Fills call_queue with _WorkItems from pending_work_items. |
| 332 | # This function never blocks. |
| 333 | while True: |
| 334 | if self.call_queue.full(): |
| 335 | return |
| 336 | try: |
| 337 | work_id = self.work_ids_queue.get(block=False) |
| 338 | except queue.Empty: |
| 339 | return |
| 340 | else: |
| 341 | work_item = self.pending_work_items[work_id] |
| 342 | |
| 343 | if work_item.future.set_running_or_notify_cancel(): |
| 344 | self.call_queue.put(_CallItem(work_id, |
| 345 | work_item.fn, |
| 346 | work_item.args, |
| 347 | work_item.kwargs), |
| 348 | block=True) |
| 349 | else: |
| 350 | del self.pending_work_items[work_id] |
| 351 | continue |
| 352 | |
| 353 | def wait_result_broken_or_wakeup(self): |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 354 | # Wait for a result to be ready in the result_queue while checking |
| 355 | # that all worker processes are still running, or for a wake up |
| 356 | # signal send. The wake up signals come either from new tasks being |
| 357 | # submitted, from the executor being shutdown/gc-ed, or from the |
| 358 | # shutdown of the python interpreter. |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 359 | result_reader = self.result_queue._reader |
| 360 | wakeup_reader = self.thread_wakeup._reader |
| 361 | readers = [result_reader, wakeup_reader] |
| 362 | worker_sentinels = [p.sentinel for p in self.processes.values()] |
Brian Quinlan | f7bda5c | 2019-05-07 13:31:11 -0400 | [diff] [blame] | 363 | ready = mp.connection.wait(readers + worker_sentinels) |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 364 | |
| 365 | cause = None |
| 366 | is_broken = True |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 367 | result_item = None |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 368 | if result_reader in ready: |
| 369 | try: |
| 370 | result_item = result_reader.recv() |
| 371 | is_broken = False |
| 372 | except BaseException as e: |
| 373 | cause = traceback.format_exception(type(e), e, e.__traceback__) |
| 374 | |
| 375 | elif wakeup_reader in ready: |
| 376 | is_broken = False |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 377 | self.thread_wakeup.clear() |
| 378 | |
| 379 | return result_item, is_broken, cause |
| 380 | |
| 381 | def process_result_item(self, result_item): |
| 382 | # Process the received a result_item. This can be either the PID of a |
| 383 | # worker that exited gracefully or a _ResultItem |
| 384 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 385 | if isinstance(result_item, int): |
| 386 | # Clean shutdown of a worker using its PID |
| 387 | # (avoids marking the executor broken) |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 388 | assert self.is_shutting_down() |
| 389 | p = self.processes.pop(result_item) |
Antoine Pitrou | d06a065 | 2011-07-16 01:13:34 +0200 | [diff] [blame] | 390 | p.join() |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 391 | if not self.processes: |
| 392 | self.join_executor_internals() |
Antoine Pitrou | 020436b | 2011-07-02 21:20:25 +0200 | [diff] [blame] | 393 | return |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 394 | else: |
| 395 | # Received a _ResultItem so mark the future as completed. |
| 396 | work_item = self.pending_work_items.pop(result_item.work_id, None) |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 397 | # work_item can be None if another process terminated (see above) |
| 398 | if work_item is not None: |
| 399 | if result_item.exception: |
| 400 | work_item.future.set_exception(result_item.exception) |
| 401 | else: |
| 402 | work_item.future.set_result(result_item.result) |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 403 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 404 | def is_shutting_down(self): |
| 405 | # Check whether we should start shutting down the executor. |
| 406 | executor = self.executor_reference() |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 407 | # No more work items can be added if: |
| 408 | # - The interpreter is shutting down OR |
| 409 | # - The executor that owns this worker has been collected OR |
| 410 | # - The executor that owns this worker has been shutdown. |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 411 | return (_global_shutdown or executor is None |
| 412 | or executor._shutdown_thread) |
Kyle Stanley | 339fd46 | 2020-02-02 07:49:00 -0500 | [diff] [blame] | 413 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 414 | def terminate_broken(self, cause): |
| 415 | # Terminate the executor because it is in a broken state. The cause |
| 416 | # argument can be used to display more information on the error that |
| 417 | # lead the executor into becoming broken. |
Kyle Stanley | 339fd46 | 2020-02-02 07:49:00 -0500 | [diff] [blame] | 418 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 419 | # Mark the process pool broken so that submits fail right now. |
| 420 | executor = self.executor_reference() |
| 421 | if executor is not None: |
| 422 | executor._broken = ('A child process terminated ' |
| 423 | 'abruptly, the process pool is not ' |
| 424 | 'usable anymore') |
| 425 | executor._shutdown_thread = True |
| 426 | executor = None |
| 427 | |
| 428 | # All pending tasks are to be marked failed with the following |
| 429 | # BrokenProcessPool error |
| 430 | bpe = BrokenProcessPool("A process in the process pool was " |
| 431 | "terminated abruptly while the future was " |
| 432 | "running or pending.") |
| 433 | if cause is not None: |
| 434 | bpe.__cause__ = _RemoteTraceback( |
| 435 | f"\n'''\n{''.join(cause)}'''") |
| 436 | |
| 437 | # Mark pending tasks as failed. |
| 438 | for work_id, work_item in self.pending_work_items.items(): |
| 439 | work_item.future.set_exception(bpe) |
| 440 | # Delete references to object. See issue16284 |
| 441 | del work_item |
| 442 | self.pending_work_items.clear() |
| 443 | |
| 444 | # Terminate remaining workers forcibly: the queues or their |
| 445 | # locks may be in a dirty state and block forever. |
| 446 | for p in self.processes.values(): |
| 447 | p.terminate() |
| 448 | |
| 449 | # clean up resources |
| 450 | self.join_executor_internals() |
| 451 | |
| 452 | def flag_executor_shutting_down(self): |
| 453 | # Flag the executor as shutting down and cancel remaining tasks if |
| 454 | # requested as early as possible if it is not gc-ed yet. |
| 455 | executor = self.executor_reference() |
| 456 | if executor is not None: |
| 457 | executor._shutdown_thread = True |
| 458 | # Cancel pending work items if requested. |
| 459 | if executor._cancel_pending_futures: |
| 460 | # Cancel all pending futures and update pending_work_items |
| 461 | # to only have futures that are currently running. |
| 462 | new_pending_work_items = {} |
| 463 | for work_id, work_item in self.pending_work_items.items(): |
| 464 | if not work_item.future.cancel(): |
| 465 | new_pending_work_items[work_id] = work_item |
| 466 | self.pending_work_items = new_pending_work_items |
| 467 | # Drain work_ids_queue since we no longer need to |
| 468 | # add items to the call queue. |
| 469 | while True: |
| 470 | try: |
| 471 | self.work_ids_queue.get_nowait() |
| 472 | except queue.Empty: |
| 473 | break |
| 474 | # Make sure we do this only once to not waste time looping |
| 475 | # on running processes over and over. |
| 476 | executor._cancel_pending_futures = False |
| 477 | |
| 478 | def shutdown_workers(self): |
| 479 | n_children_to_stop = self.get_n_children_alive() |
| 480 | n_sentinels_sent = 0 |
| 481 | # Send the right number of sentinels, to make sure all children are |
| 482 | # properly terminated. |
| 483 | while (n_sentinels_sent < n_children_to_stop |
| 484 | and self.get_n_children_alive() > 0): |
| 485 | for i in range(n_children_to_stop - n_sentinels_sent): |
| 486 | try: |
| 487 | self.call_queue.put_nowait(None) |
| 488 | n_sentinels_sent += 1 |
| 489 | except queue.Full: |
| 490 | break |
| 491 | |
| 492 | def join_executor_internals(self): |
| 493 | self.shutdown_workers() |
| 494 | # Release the queue's resources as soon as possible. |
| 495 | self.call_queue.close() |
| 496 | self.call_queue.join_thread() |
| 497 | self.thread_wakeup.close() |
| 498 | # If .join() is not called on the created processes then |
| 499 | # some ctx.Queue methods may deadlock on Mac OS X. |
| 500 | for p in self.processes.values(): |
| 501 | p.join() |
| 502 | |
| 503 | def get_n_children_alive(self): |
| 504 | # This is an upper bound on the number of children alive. |
| 505 | return sum(p.is_alive() for p in self.processes.values()) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 506 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 507 | |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 508 | _system_limits_checked = False |
| 509 | _system_limited = None |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 510 | |
| 511 | |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 512 | def _check_system_limits(): |
| 513 | global _system_limits_checked, _system_limited |
| 514 | if _system_limits_checked: |
| 515 | if _system_limited: |
| 516 | raise NotImplementedError(_system_limited) |
| 517 | _system_limits_checked = True |
| 518 | try: |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 519 | nsems_max = os.sysconf("SC_SEM_NSEMS_MAX") |
| 520 | except (AttributeError, ValueError): |
| 521 | # sysconf not available or setting not available |
| 522 | return |
| 523 | if nsems_max == -1: |
Ezio Melotti | b5bc353 | 2013-08-17 16:11:40 +0300 | [diff] [blame] | 524 | # indetermined limit, assume that limit is determined |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 525 | # by available memory only |
| 526 | return |
| 527 | if nsems_max >= 256: |
| 528 | # minimum number of semaphores available |
| 529 | # according to POSIX |
| 530 | return |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 531 | _system_limited = ("system provides too few semaphores (%d" |
| 532 | " available, 256 necessary)" % nsems_max) |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 533 | raise NotImplementedError(_system_limited) |
| 534 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 535 | |
Grzegorz Grzywacz | 97e1b1c | 2017-09-01 18:54:00 +0200 | [diff] [blame] | 536 | def _chain_from_iterable_of_lists(iterable): |
| 537 | """ |
| 538 | Specialized implementation of itertools.chain.from_iterable. |
| 539 | Each item in *iterable* should be a list. This function is |
| 540 | careful not to keep references to yielded objects. |
| 541 | """ |
| 542 | for element in iterable: |
| 543 | element.reverse() |
| 544 | while element: |
| 545 | yield element.pop() |
| 546 | |
| 547 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 548 | class BrokenProcessPool(_base.BrokenExecutor): |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 549 | """ |
| 550 | Raised when a process in a ProcessPoolExecutor terminated abruptly |
| 551 | while a future was in the running state. |
| 552 | """ |
| 553 | |
| 554 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 555 | class ProcessPoolExecutor(_base.Executor): |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 556 | def __init__(self, max_workers=None, mp_context=None, |
| 557 | initializer=None, initargs=()): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 558 | """Initializes a new ProcessPoolExecutor instance. |
| 559 | |
| 560 | Args: |
| 561 | max_workers: The maximum number of processes that can be used to |
| 562 | execute the given calls. If None or not given then as many |
| 563 | worker processes will be created as the machine has processors. |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 564 | mp_context: A multiprocessing context to launch the workers. This |
| 565 | object should provide SimpleQueue, Queue and Process. |
ubordignon | 552ace7 | 2019-06-15 13:43:10 +0200 | [diff] [blame] | 566 | initializer: A callable used to initialize worker processes. |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 567 | initargs: A tuple of arguments to pass to the initializer. |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 568 | """ |
Martin v. Löwis | 9f6d48b | 2011-01-03 00:07:01 +0000 | [diff] [blame] | 569 | _check_system_limits() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 570 | |
| 571 | if max_workers is None: |
Charles-François Natali | 37cfb0a | 2013-06-28 19:25:45 +0200 | [diff] [blame] | 572 | self._max_workers = os.cpu_count() or 1 |
Brian Quinlan | 3988986 | 2019-05-08 14:04:53 -0400 | [diff] [blame] | 573 | if sys.platform == 'win32': |
| 574 | self._max_workers = min(_MAX_WINDOWS_WORKERS, |
| 575 | self._max_workers) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 576 | else: |
Brian Quinlan | 20efceb | 2014-05-17 13:51:10 -0700 | [diff] [blame] | 577 | if max_workers <= 0: |
| 578 | raise ValueError("max_workers must be greater than 0") |
Brian Quinlan | 3988986 | 2019-05-08 14:04:53 -0400 | [diff] [blame] | 579 | elif (sys.platform == 'win32' and |
| 580 | max_workers > _MAX_WINDOWS_WORKERS): |
| 581 | raise ValueError( |
| 582 | f"max_workers must be <= {_MAX_WINDOWS_WORKERS}") |
Brian Quinlan | 20efceb | 2014-05-17 13:51:10 -0700 | [diff] [blame] | 583 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 584 | self._max_workers = max_workers |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 585 | |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 586 | if mp_context is None: |
| 587 | mp_context = mp.get_context() |
| 588 | self._mp_context = mp_context |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 589 | |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 590 | if initializer is not None and not callable(initializer): |
| 591 | raise TypeError("initializer must be a callable") |
| 592 | self._initializer = initializer |
| 593 | self._initargs = initargs |
| 594 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 595 | # Management thread |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 596 | self._executor_manager_thread = None |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 597 | |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 598 | # Map of pids to processes |
| 599 | self._processes = {} |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 600 | |
| 601 | # Shutdown is a two-step process. |
| 602 | self._shutdown_thread = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 603 | self._shutdown_lock = threading.Lock() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 604 | self._broken = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 605 | self._queue_count = 0 |
| 606 | self._pending_work_items = {} |
Kyle Stanley | 339fd46 | 2020-02-02 07:49:00 -0500 | [diff] [blame] | 607 | self._cancel_pending_futures = False |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 608 | |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 609 | # _ThreadWakeup is a communication channel used to interrupt the wait |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 610 | # of the main loop of executor_manager_thread from another thread (e.g. |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 611 | # when calling executor.submit or executor.shutdown). We do not use the |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 612 | # _result_queue to send wakeup signals to the executor_manager_thread |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 613 | # as it could result in a deadlock if a worker process dies with the |
| 614 | # _result_queue write lock still acquired. |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 615 | self._executor_manager_thread_wakeup = _ThreadWakeup() |
Thomas Moreau | 94459fd | 2018-01-05 11:15:54 +0100 | [diff] [blame] | 616 | |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 617 | # Create communication channels for the executor |
| 618 | # Make the call queue slightly larger than the number of processes to |
| 619 | # prevent the worker processes from idling. But don't make it too big |
| 620 | # because futures in the call queue cannot be cancelled. |
| 621 | queue_size = self._max_workers + EXTRA_QUEUED_CALLS |
| 622 | self._call_queue = _SafeQueue( |
| 623 | max_size=queue_size, ctx=self._mp_context, |
| 624 | pending_work_items=self._pending_work_items, |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 625 | thread_wakeup=self._executor_manager_thread_wakeup) |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 626 | # Killed worker processes can produce spurious "broken pipe" |
| 627 | # tracebacks in the queue's own worker thread. But we detect killed |
| 628 | # processes anyway, so silence the tracebacks. |
| 629 | self._call_queue._ignore_epipe = True |
| 630 | self._result_queue = mp_context.SimpleQueue() |
| 631 | self._work_ids = queue.Queue() |
| 632 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 633 | def _start_executor_manager_thread(self): |
| 634 | if self._executor_manager_thread is None: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 635 | # Start the processes so that their sentinels are known. |
| 636 | self._adjust_process_count() |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 637 | self._executor_manager_thread = _ExecutorManagerThread(self) |
| 638 | self._executor_manager_thread.start() |
| 639 | _threads_wakeups[self._executor_manager_thread] = \ |
| 640 | self._executor_manager_thread_wakeup |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 641 | |
| 642 | def _adjust_process_count(self): |
| 643 | for _ in range(len(self._processes), self._max_workers): |
Thomas Moreau | e8c368d | 2017-10-03 11:53:17 +0200 | [diff] [blame] | 644 | p = self._mp_context.Process( |
| 645 | target=_process_worker, |
| 646 | args=(self._call_queue, |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 647 | self._result_queue, |
| 648 | self._initializer, |
| 649 | self._initargs)) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 650 | p.start() |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 651 | self._processes[p.pid] = p |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 652 | |
Serhiy Storchaka | 142566c | 2019-06-05 18:22:31 +0300 | [diff] [blame] | 653 | def submit(self, fn, /, *args, **kwargs): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 654 | with self._shutdown_lock: |
Antoine Pitrou | dd69649 | 2011-06-08 17:21:55 +0200 | [diff] [blame] | 655 | if self._broken: |
Antoine Pitrou | 63ff413 | 2017-11-04 11:05:49 +0100 | [diff] [blame] | 656 | raise BrokenProcessPool(self._broken) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 657 | if self._shutdown_thread: |
| 658 | raise RuntimeError('cannot schedule new futures after shutdown') |
Mark Nemec | c4b695f | 2018-04-10 18:23:14 +0100 | [diff] [blame] | 659 | if _global_shutdown: |
| 660 | raise RuntimeError('cannot schedule new futures after ' |
| 661 | 'interpreter shutdown') |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 662 | |
| 663 | f = _base.Future() |
| 664 | w = _WorkItem(f, fn, args, kwargs) |
| 665 | |
| 666 | self._pending_work_items[self._queue_count] = w |
| 667 | self._work_ids.put(self._queue_count) |
| 668 | self._queue_count += 1 |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 669 | # Wake up queue management thread |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 670 | self._executor_manager_thread_wakeup.wakeup() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 671 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 672 | self._start_executor_manager_thread() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 673 | return f |
| 674 | submit.__doc__ = _base.Executor.submit.__doc__ |
| 675 | |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 676 | def map(self, fn, *iterables, timeout=None, chunksize=1): |
Martin Panter | d2ad571 | 2015-11-02 04:20:33 +0000 | [diff] [blame] | 677 | """Returns an iterator equivalent to map(fn, iter). |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 678 | |
| 679 | Args: |
| 680 | fn: A callable that will take as many arguments as there are |
| 681 | passed iterables. |
| 682 | timeout: The maximum number of seconds to wait. If None, then there |
| 683 | is no limit on the wait time. |
| 684 | chunksize: If greater than one, the iterables will be chopped into |
| 685 | chunks of size chunksize and submitted to the process pool. |
| 686 | If set to one, the items in the list will be sent one at a time. |
| 687 | |
| 688 | Returns: |
| 689 | An iterator equivalent to: map(func, *iterables) but the calls may |
| 690 | be evaluated out-of-order. |
| 691 | |
| 692 | Raises: |
| 693 | TimeoutError: If the entire result iterator could not be generated |
| 694 | before the given timeout. |
| 695 | Exception: If fn(*args) raises for any values. |
| 696 | """ |
| 697 | if chunksize < 1: |
| 698 | raise ValueError("chunksize must be >= 1.") |
| 699 | |
| 700 | results = super().map(partial(_process_chunk, fn), |
| 701 | _get_chunks(*iterables, chunksize=chunksize), |
| 702 | timeout=timeout) |
Grzegorz Grzywacz | 97e1b1c | 2017-09-01 18:54:00 +0200 | [diff] [blame] | 703 | return _chain_from_iterable_of_lists(results) |
Antoine Pitrou | 4aae276 | 2014-10-04 20:20:10 +0200 | [diff] [blame] | 704 | |
Kyle Stanley | 339fd46 | 2020-02-02 07:49:00 -0500 | [diff] [blame] | 705 | def shutdown(self, wait=True, *, cancel_futures=False): |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 706 | with self._shutdown_lock: |
Kyle Stanley | 339fd46 | 2020-02-02 07:49:00 -0500 | [diff] [blame] | 707 | self._cancel_pending_futures = cancel_futures |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 708 | self._shutdown_thread = True |
Kyle Stanley | 339fd46 | 2020-02-02 07:49:00 -0500 | [diff] [blame] | 709 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 710 | if self._executor_manager_thread: |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 711 | # Wake up queue management thread |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 712 | self._executor_manager_thread_wakeup.wakeup() |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 713 | if wait: |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 714 | self._executor_manager_thread.join() |
Ezio Melotti | b5bc353 | 2013-08-17 16:11:40 +0300 | [diff] [blame] | 715 | # To reduce the risk of opening too many files, remove references to |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 716 | # objects that use file descriptors. |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 717 | self._executor_manager_thread = None |
Thomas Moreau | a5cbab5 | 2020-02-16 19:09:26 +0100 | [diff] [blame] | 718 | self._call_queue = None |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 719 | self._result_queue = None |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 720 | self._processes = None |
Thomas Moreau | 095ee41 | 2018-03-12 18:18:41 +0100 | [diff] [blame] | 721 | |
Thomas Moreau | 0e89076 | 2020-03-01 21:49:14 +0100 | [diff] [blame] | 722 | if self._executor_manager_thread_wakeup: |
| 723 | self._executor_manager_thread_wakeup = None |
Thomas Moreau | 095ee41 | 2018-03-12 18:18:41 +0100 | [diff] [blame] | 724 | |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 725 | shutdown.__doc__ = _base.Executor.shutdown.__doc__ |