process_executor.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. ###############################################################################
  2. # Re-implementation of the ProcessPoolExecutor more robust to faults
  3. #
  4. # author: Thomas Moreau and Olivier Grisel
  5. #
  6. # adapted from concurrent/futures/process_pool_executor.py (17/02/2017)
  7. # * Add an extra management thread to detect executor_manager_thread failures,
  8. # * Improve the shutdown process to avoid deadlocks,
  9. # * Add timeout for workers,
  10. # * More robust pickling process.
  11. #
  12. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  13. # Licensed to PSF under a Contributor Agreement.
  14. """Implements ProcessPoolExecutor.
  15. The follow diagram and text describe the data-flow through the system:
  16. |======================= In-process =====================|== Out-of-process ==|
  17. +----------+ +----------+ +--------+ +-----------+ +---------+
  18. | | => | Work Ids | | | | Call Q | | Process |
  19. | | +----------+ | | +-----------+ | Pool |
  20. | | | ... | | | | ... | +---------+
  21. | | | 6 | => | | => | 5, call() | => | |
  22. | | | 7 | | | | ... | | |
  23. | Process | | ... | | Local | +-----------+ | Process |
  24. | Pool | +----------+ | Worker | | #1..n |
  25. | Executor | | Thread | | |
  26. | | +----------- + | | +-----------+ | |
  27. | | <=> | Work Items | <=> | | <= | Result Q | <= | |
  28. | | +------------+ | | +-----------+ | |
  29. | | | 6: call() | | | | ... | | |
  30. | | | future | +--------+ | 4, result | | |
  31. | | | ... | | 3, except | | |
  32. +----------+ +------------+ +-----------+ +---------+
  33. Executor.submit() called:
  34. - creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict
  35. - adds the id of the _WorkItem to the "Work Ids" queue
  36. Local worker thread:
  37. - reads work ids from the "Work Ids" queue and looks up the corresponding
  38. WorkItem from the "Work Items" dict: if the work item has been cancelled then
  39. it is simply removed from the dict, otherwise it is repackaged as a
  40. _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q"
  41. until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because
  42. calls placed in the "Call Q" can no longer be cancelled with Future.cancel().
  43. - reads _ResultItems from "Result Q", updates the future stored in the
  44. "Work Items" dict and deletes the dict entry
  45. Process #1..n:
  46. - reads _CallItems from "Call Q", executes the calls, and puts the resulting
  47. _ResultItems in "Result Q"
  48. """
  49. __author__ = "Thomas Moreau (thomas.moreau.2010@gmail.com)"
  50. import faulthandler
  51. import os
  52. import gc
  53. import sys
  54. import queue
  55. import struct
  56. import weakref
  57. import warnings
  58. import itertools
  59. import traceback
  60. import threading
  61. from time import time, sleep
  62. import multiprocessing as mp
  63. from functools import partial
  64. from pickle import PicklingError
  65. from concurrent.futures import Executor
  66. from concurrent.futures._base import LOGGER
  67. from concurrent.futures.process import BrokenProcessPool as _BPPException
  68. from multiprocessing.connection import wait
  69. from ._base import Future
  70. from .backend import get_context
  71. from .backend.context import cpu_count, _MAX_WINDOWS_WORKERS
  72. from .backend.queues import Queue, SimpleQueue
  73. from .backend.reduction import set_loky_pickler, get_loky_pickler_name
  74. from .backend.utils import kill_process_tree, get_exitcodes_terminated_worker
  75. from .initializers import _prepare_initializer
  76. # Mechanism to prevent infinite process spawning. When a worker of a
  77. # ProcessPoolExecutor nested in MAX_DEPTH Executor tries to create a new
  78. # Executor, a LokyRecursionError is raised
  79. MAX_DEPTH = int(os.environ.get("LOKY_MAX_DEPTH", 10))
  80. _CURRENT_DEPTH = 0
  81. # Minimum time interval between two consecutive memory leak protection checks.
  82. _MEMORY_LEAK_CHECK_DELAY = 1.0
  83. # Number of bytes of memory usage allowed over the reference process size.
  84. _MAX_MEMORY_LEAK_SIZE = int(3e8)
  85. try:
  86. from psutil import Process
  87. _USE_PSUTIL = True
  88. def _get_memory_usage(pid, force_gc=False):
  89. if force_gc:
  90. gc.collect()
  91. mem_size = Process(pid).memory_info().rss
  92. mp.util.debug(f"psutil return memory size: {mem_size}")
  93. return mem_size
  94. except ImportError:
  95. _USE_PSUTIL = False
  96. class _ThreadWakeup:
  97. def __init__(self):
  98. self._closed = False
  99. self._reader, self._writer = mp.Pipe(duplex=False)
  100. def close(self):
  101. if not self._closed:
  102. self._closed = True
  103. self._writer.close()
  104. self._reader.close()
  105. def wakeup(self):
  106. if not self._closed:
  107. self._writer.send_bytes(b"")
  108. def clear(self):
  109. if not self._closed:
  110. while self._reader.poll():
  111. self._reader.recv_bytes()
  112. class _ExecutorFlags:
  113. """necessary references to maintain executor states without preventing gc
  114. It permits to keep the information needed by executor_manager_thread
  115. and crash_detection_thread to maintain the pool without preventing the
  116. garbage collection of unreferenced executors.
  117. """
  118. def __init__(self, shutdown_lock):
  119. self.shutdown = False
  120. self.broken = None
  121. self.kill_workers = False
  122. self.shutdown_lock = shutdown_lock
  123. def flag_as_shutting_down(self, kill_workers=None):
  124. with self.shutdown_lock:
  125. self.shutdown = True
  126. if kill_workers is not None:
  127. self.kill_workers = kill_workers
  128. def flag_as_broken(self, broken):
  129. with self.shutdown_lock:
  130. self.shutdown = True
  131. self.broken = broken
  132. # Prior to 3.9, executor_manager_thread is created as daemon thread. This means
  133. # that it is not joined automatically when the interpreter is shutting down.
  134. # To work around this problem, an exit handler is installed to tell the
  135. # thread to exit when the interpreter is shutting down and then waits until
  136. # it finishes. The thread needs to be daemonized because the atexit hooks are
  137. # called after all non daemonized threads are joined.
  138. #
  139. # Starting 3.9, there exists a specific atexit hook to be called before joining
  140. # the threads so the executor_manager_thread does not need to be daemonized
  141. # anymore.
  142. #
  143. # The atexit hooks are registered when starting the first ProcessPoolExecutor
  144. # to avoid import having an effect on the interpreter.
  145. _global_shutdown = False
  146. _global_shutdown_lock = threading.Lock()
  147. _threads_wakeups = weakref.WeakKeyDictionary()
  148. def _python_exit():
  149. global _global_shutdown
  150. _global_shutdown = True
  151. # Materialize the list of items to avoid error due to iterating over
  152. # changing size dictionary.
  153. items = list(_threads_wakeups.items())
  154. if len(items) > 0:
  155. mp.util.debug(
  156. f"Interpreter shutting down. Waking up {len(items)}"
  157. f"executor_manager_thread:\n{items}"
  158. )
  159. # Wake up the executor_manager_thread's so they can detect the interpreter
  160. # is shutting down and exit.
  161. for _, (shutdown_lock, thread_wakeup) in items:
  162. with shutdown_lock:
  163. thread_wakeup.wakeup()
  164. # Collect the executor_manager_thread's to make sure we exit cleanly.
  165. for thread, _ in items:
  166. # This locks is to prevent situations where an executor is gc'ed in one
  167. # thread while the atexit finalizer is running in another thread.
  168. with _global_shutdown_lock:
  169. thread.join()
  170. # With the fork context, _thread_wakeups is propagated to children.
  171. # Clear it after fork to avoid some situation that can cause some
  172. # freeze when joining the workers.
  173. mp.util.register_after_fork(_threads_wakeups, lambda obj: obj.clear())
  174. # Module variable to register the at_exit call
  175. process_pool_executor_at_exit = None
  176. # Controls how many more calls than processes will be queued in the call queue.
  177. # A smaller number will mean that processes spend more time idle waiting for
  178. # work while a larger number will make Future.cancel() succeed less frequently
  179. # (Futures in the call queue cannot be cancelled).
  180. EXTRA_QUEUED_CALLS = 1
  181. class _RemoteTraceback(Exception):
  182. """Embed stringification of remote traceback in local traceback"""
  183. def __init__(self, tb=None):
  184. self.tb = f'\n"""\n{tb}"""'
  185. def __str__(self):
  186. return self.tb
  187. # Do not inherit from BaseException to mirror
  188. # concurrent.futures.process._ExceptionWithTraceback
  189. class _ExceptionWithTraceback:
  190. def __init__(self, exc):
  191. tb = getattr(exc, "__traceback__", None)
  192. if tb is None:
  193. _, _, tb = sys.exc_info()
  194. tb = traceback.format_exception(type(exc), exc, tb)
  195. tb = "".join(tb)
  196. self.exc = exc
  197. self.tb = tb
  198. def __reduce__(self):
  199. return _rebuild_exc, (self.exc, self.tb)
  200. def _rebuild_exc(exc, tb):
  201. exc.__cause__ = _RemoteTraceback(tb)
  202. return exc
  203. class _WorkItem:
  204. __slots__ = ["future", "fn", "args", "kwargs"]
  205. def __init__(self, future, fn, args, kwargs):
  206. self.future = future
  207. self.fn = fn
  208. self.args = args
  209. self.kwargs = kwargs
  210. class _ResultItem:
  211. def __init__(self, work_id, exception=None, result=None):
  212. self.work_id = work_id
  213. self.exception = exception
  214. self.result = result
  215. class _CallItem:
  216. def __init__(self, work_id, fn, args, kwargs):
  217. self.work_id = work_id
  218. self.fn = fn
  219. self.args = args
  220. self.kwargs = kwargs
  221. # Store the current loky_pickler so it is correctly set in the worker
  222. self.loky_pickler = get_loky_pickler_name()
  223. def __call__(self):
  224. set_loky_pickler(self.loky_pickler)
  225. return self.fn(*self.args, **self.kwargs)
  226. def __repr__(self):
  227. return (
  228. f"CallItem({self.work_id}, {self.fn}, {self.args}, {self.kwargs})"
  229. )
  230. class _SafeQueue(Queue):
  231. """Safe Queue set exception to the future object linked to a job"""
  232. def __init__(
  233. self,
  234. max_size=0,
  235. ctx=None,
  236. pending_work_items=None,
  237. running_work_items=None,
  238. thread_wakeup=None,
  239. shutdown_lock=None,
  240. reducers=None,
  241. ):
  242. self.thread_wakeup = thread_wakeup
  243. self.shutdown_lock = shutdown_lock
  244. self.pending_work_items = pending_work_items
  245. self.running_work_items = running_work_items
  246. super().__init__(max_size, reducers=reducers, ctx=ctx)
  247. def _on_queue_feeder_error(self, e, obj):
  248. if isinstance(obj, _CallItem):
  249. # format traceback only works on python3
  250. if isinstance(e, struct.error):
  251. raised_error = RuntimeError(
  252. "The task could not be sent to the workers as it is too "
  253. "large for `send_bytes`."
  254. )
  255. else:
  256. raised_error = PicklingError(
  257. "Could not pickle the task to send it to the workers."
  258. )
  259. tb = traceback.format_exception(
  260. type(e), e, getattr(e, "__traceback__", None)
  261. )
  262. raised_error.__cause__ = _RemoteTraceback("".join(tb))
  263. work_item = self.pending_work_items.pop(obj.work_id, None)
  264. self.running_work_items.remove(obj.work_id)
  265. # work_item can be None if another process terminated. In this
  266. # case, the executor_manager_thread fails all work_items with
  267. # BrokenProcessPool
  268. if work_item is not None:
  269. work_item.future.set_exception(raised_error)
  270. del work_item
  271. with self.shutdown_lock:
  272. self.thread_wakeup.wakeup()
  273. else:
  274. super()._on_queue_feeder_error(e, obj)
  275. def _get_chunks(chunksize, *iterables):
  276. """Iterates over zip()ed iterables in chunks."""
  277. it = zip(*iterables)
  278. while True:
  279. chunk = tuple(itertools.islice(it, chunksize))
  280. if not chunk:
  281. return
  282. yield chunk
  283. def _process_chunk(fn, chunk):
  284. """Processes a chunk of an iterable passed to map.
  285. Runs the function passed to map() on a chunk of the
  286. iterable passed to map.
  287. This function is run in a separate process.
  288. """
  289. return [fn(*args) for args in chunk]
  290. def _sendback_result(result_queue, work_id, result=None, exception=None):
  291. """Safely send back the given result or exception"""
  292. try:
  293. result_queue.put(
  294. _ResultItem(work_id, result=result, exception=exception)
  295. )
  296. except BaseException as e:
  297. exc = _ExceptionWithTraceback(e)
  298. result_queue.put(_ResultItem(work_id, exception=exc))
  299. def _enable_faulthandler_if_needed():
  300. if "PYTHONFAULTHANDLER" in os.environ:
  301. # Respect the environment variable to configure faulthandler. This
  302. # makes it possible to never enable faulthandler in the loky workers by
  303. # setting PYTHONFAULTHANDLER=0 explicitly in the environment.
  304. mp.util.debug(
  305. f"faulthandler explicitly configured by environment variable: "
  306. f"PYTHONFAULTHANDLER={os.environ['PYTHONFAULTHANDLER']}."
  307. )
  308. else:
  309. if faulthandler.is_enabled():
  310. # Fault handler is already enabled, possibly via a custom
  311. # initializer to customize the behavior.
  312. mp.util.debug("faulthandler already enabled.")
  313. else:
  314. # Enable faulthandler by default with default paramaters otherwise.
  315. mp.util.debug(
  316. "Enabling faulthandler to report tracebacks on worker crashes."
  317. )
  318. faulthandler.enable()
  319. def _process_worker(
  320. call_queue,
  321. result_queue,
  322. initializer,
  323. initargs,
  324. processes_management_lock,
  325. timeout,
  326. worker_exit_lock,
  327. current_depth,
  328. ):
  329. """Evaluates calls from call_queue and places the results in result_queue.
  330. This worker is run in a separate process.
  331. Args:
  332. call_queue: A ctx.Queue of _CallItems that will be read and
  333. evaluated by the worker.
  334. result_queue: A ctx.Queue of _ResultItems that will written
  335. to by the worker.
  336. initializer: A callable initializer, or None
  337. initargs: A tuple of args for the initializer
  338. processes_management_lock: A ctx.Lock avoiding worker timeout while
  339. some workers are being spawned.
  340. timeout: maximum time to wait for a new item in the call_queue. If that
  341. time is expired, the worker will shutdown.
  342. worker_exit_lock: Lock to avoid flagging the executor as broken on
  343. workers timeout.
  344. current_depth: Nested parallelism level, to avoid infinite spawning.
  345. """
  346. if initializer is not None:
  347. try:
  348. initializer(*initargs)
  349. except BaseException:
  350. LOGGER.critical("Exception in initializer:", exc_info=True)
  351. # The parent will notice that the process stopped and
  352. # mark the pool broken
  353. return
  354. # set the global _CURRENT_DEPTH mechanism to limit recursive call
  355. global _CURRENT_DEPTH
  356. _CURRENT_DEPTH = current_depth
  357. _process_reference_size = None
  358. _last_memory_leak_check = None
  359. pid = os.getpid()
  360. mp.util.debug(f"Worker started with timeout={timeout}")
  361. _enable_faulthandler_if_needed()
  362. while True:
  363. try:
  364. call_item = call_queue.get(block=True, timeout=timeout)
  365. if call_item is None:
  366. mp.util.info("Shutting down worker on sentinel")
  367. except queue.Empty:
  368. mp.util.info(f"Shutting down worker after timeout {timeout:0.3f}s")
  369. if processes_management_lock.acquire(block=False):
  370. processes_management_lock.release()
  371. call_item = None
  372. else:
  373. mp.util.info("Could not acquire processes_management_lock")
  374. continue
  375. except BaseException:
  376. previous_tb = traceback.format_exc()
  377. try:
  378. result_queue.put(_RemoteTraceback(previous_tb))
  379. except BaseException:
  380. # If we cannot format correctly the exception, at least print
  381. # the traceback.
  382. print(previous_tb)
  383. mp.util.debug("Exiting with code 1")
  384. sys.exit(1)
  385. if call_item is None:
  386. # Notify queue management thread about worker shutdown
  387. result_queue.put(pid)
  388. is_clean = worker_exit_lock.acquire(True, timeout=30)
  389. # Early notify any loky executor running in this worker process
  390. # (nested parallelism) that this process is about to shutdown to
  391. # avoid a deadlock waiting undifinitely for the worker to finish.
  392. _python_exit()
  393. if is_clean:
  394. mp.util.debug("Exited cleanly")
  395. else:
  396. mp.util.info("Main process did not release worker_exit")
  397. return
  398. try:
  399. r = call_item()
  400. except BaseException as e:
  401. exc = _ExceptionWithTraceback(e)
  402. result_queue.put(_ResultItem(call_item.work_id, exception=exc))
  403. else:
  404. _sendback_result(result_queue, call_item.work_id, result=r)
  405. del r
  406. # Free the resource as soon as possible, to avoid holding onto
  407. # open files or shared memory that is not needed anymore
  408. del call_item
  409. if _USE_PSUTIL:
  410. if _process_reference_size is None:
  411. # Make reference measurement after the first call
  412. _process_reference_size = _get_memory_usage(pid, force_gc=True)
  413. _last_memory_leak_check = time()
  414. continue
  415. if time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY:
  416. mem_usage = _get_memory_usage(pid)
  417. _last_memory_leak_check = time()
  418. if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE:
  419. # Memory usage stays within bounds: everything is fine.
  420. continue
  421. # Check again memory usage; this time take the measurement
  422. # after a forced garbage collection to break any reference
  423. # cycles.
  424. mem_usage = _get_memory_usage(pid, force_gc=True)
  425. _last_memory_leak_check = time()
  426. if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE:
  427. # The GC managed to free the memory: everything is fine.
  428. continue
  429. # The process is leaking memory: let the master process
  430. # know that we need to start a new worker.
  431. mp.util.info("Memory leak detected: shutting down worker")
  432. result_queue.put(pid)
  433. with worker_exit_lock:
  434. mp.util.debug("Exit due to memory leak")
  435. return
  436. else:
  437. # if psutil is not installed, trigger gc.collect events
  438. # regularly to limit potential memory leaks due to reference cycles
  439. if _last_memory_leak_check is None or (
  440. time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY
  441. ):
  442. gc.collect()
  443. _last_memory_leak_check = time()
  444. class _ExecutorManagerThread(threading.Thread):
  445. """Manages the communication between this process and the worker processes.
  446. The manager is run in a local thread.
  447. Args:
  448. executor: A reference to the ProcessPoolExecutor that owns
  449. this thread. A weakref will be own by the manager as well as
  450. references to internal objects used to introspect the state of
  451. the executor.
  452. """
  453. def __init__(self, executor):
  454. # Store references to necessary internals of the executor.
  455. # A _ThreadWakeup to allow waking up the executor_manager_thread from
  456. # the main Thread and avoid deadlocks caused by permanently
  457. # locked queues.
  458. self.thread_wakeup = executor._executor_manager_thread_wakeup
  459. self.shutdown_lock = executor._shutdown_lock
  460. # A weakref.ref to the ProcessPoolExecutor that owns this thread. Used
  461. # to determine if the ProcessPoolExecutor has been garbage collected
  462. # and that the manager can exit.
  463. # When the executor gets garbage collected, the weakref callback
  464. # will wake up the queue management thread so that it can terminate
  465. # if there is no pending work item.
  466. def weakref_cb(
  467. _,
  468. thread_wakeup=self.thread_wakeup,
  469. shutdown_lock=self.shutdown_lock,
  470. ):
  471. if mp is not None:
  472. # At this point, the multiprocessing module can already be
  473. # garbage collected. We only log debug info when still
  474. # possible.
  475. mp.util.debug(
  476. "Executor collected: triggering callback for"
  477. " QueueManager wakeup"
  478. )
  479. with shutdown_lock:
  480. thread_wakeup.wakeup()
  481. self.executor_reference = weakref.ref(executor, weakref_cb)
  482. # The flags of the executor
  483. self.executor_flags = executor._flags
  484. # A list of the ctx.Process instances used as workers.
  485. self.processes = executor._processes
  486. # A ctx.Queue that will be filled with _CallItems derived from
  487. # _WorkItems for processing by the process workers.
  488. self.call_queue = executor._call_queue
  489. # A ctx.SimpleQueue of _ResultItems generated by the process workers.
  490. self.result_queue = executor._result_queue
  491. # A queue.Queue of work ids e.g. Queue([5, 6, ...]).
  492. self.work_ids_queue = executor._work_ids
  493. # A dict mapping work ids to _WorkItems e.g.
  494. # {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  495. self.pending_work_items = executor._pending_work_items
  496. # A list of the work_ids that are currently running
  497. self.running_work_items = executor._running_work_items
  498. # A lock to avoid concurrent shutdown of workers on timeout and spawn
  499. # of new processes or shut down
  500. self.processes_management_lock = executor._processes_management_lock
  501. super().__init__(name="ExecutorManagerThread")
  502. if sys.version_info < (3, 9):
  503. self.daemon = True
  504. def run(self):
  505. # Main loop for the executor manager thread.
  506. while True:
  507. self.add_call_item_to_queue()
  508. result_item, is_broken, bpe = self.wait_result_broken_or_wakeup()
  509. if is_broken:
  510. self.terminate_broken(bpe)
  511. return
  512. if result_item is not None:
  513. self.process_result_item(result_item)
  514. # Delete reference to result_item to avoid keeping references
  515. # while waiting on new results.
  516. del result_item
  517. if self.is_shutting_down():
  518. self.flag_executor_shutting_down()
  519. # Since no new work items can be added, it is safe to shutdown
  520. # this thread if there are no pending work items.
  521. if not self.pending_work_items:
  522. self.join_executor_internals()
  523. return
  524. def add_call_item_to_queue(self):
  525. # Fills call_queue with _WorkItems from pending_work_items.
  526. # This function never blocks.
  527. while True:
  528. if self.call_queue.full():
  529. return
  530. try:
  531. work_id = self.work_ids_queue.get(block=False)
  532. except queue.Empty:
  533. return
  534. else:
  535. work_item = self.pending_work_items[work_id]
  536. if work_item.future.set_running_or_notify_cancel():
  537. self.running_work_items += [work_id]
  538. self.call_queue.put(
  539. _CallItem(
  540. work_id,
  541. work_item.fn,
  542. work_item.args,
  543. work_item.kwargs,
  544. ),
  545. block=True,
  546. )
  547. else:
  548. del self.pending_work_items[work_id]
  549. continue
  550. def wait_result_broken_or_wakeup(self):
  551. # Wait for a result to be ready in the result_queue while checking
  552. # that all worker processes are still running, or for a wake up
  553. # signal send. The wake up signals come either from new tasks being
  554. # submitted, from the executor being shutdown/gc-ed, or from the
  555. # shutdown of the python interpreter.
  556. result_reader = self.result_queue._reader
  557. wakeup_reader = self.thread_wakeup._reader
  558. readers = [result_reader, wakeup_reader]
  559. worker_sentinels = [p.sentinel for p in list(self.processes.values())]
  560. ready = wait(readers + worker_sentinels)
  561. bpe = None
  562. is_broken = True
  563. result_item = None
  564. if result_reader in ready:
  565. try:
  566. result_item = result_reader.recv()
  567. if isinstance(result_item, _RemoteTraceback):
  568. bpe = BrokenProcessPool(
  569. "A task has failed to un-serialize. Please ensure that"
  570. " the arguments of the function are all picklable."
  571. )
  572. bpe.__cause__ = result_item
  573. else:
  574. is_broken = False
  575. except BaseException as e:
  576. bpe = BrokenProcessPool(
  577. "A result has failed to un-serialize. Please ensure that "
  578. "the objects returned by the function are always "
  579. "picklable."
  580. )
  581. tb = traceback.format_exception(
  582. type(e), e, getattr(e, "__traceback__", None)
  583. )
  584. bpe.__cause__ = _RemoteTraceback("".join(tb))
  585. elif wakeup_reader in ready:
  586. # This is simply a wake-up event that might either trigger putting
  587. # more tasks in the queue or trigger the clean up of resources.
  588. is_broken = False
  589. else:
  590. # A worker has terminated and we don't know why, set the state of
  591. # the executor as broken
  592. exit_codes = ""
  593. if sys.platform != "win32":
  594. # In Windows, introspecting terminated workers exitcodes seems
  595. # unstable, therefore they are not appended in the exception
  596. # message.
  597. exit_codes = (
  598. "\nThe exit codes of the workers are "
  599. f"{get_exitcodes_terminated_worker(self.processes)}"
  600. )
  601. mp.util.debug(
  602. "A worker unexpectedly terminated. Workers that "
  603. "might have caused the breakage: "
  604. + str(
  605. {
  606. p.name: p.exitcode
  607. for p in list(self.processes.values())
  608. if p is not None and p.sentinel in ready
  609. }
  610. )
  611. )
  612. bpe = TerminatedWorkerError(
  613. "A worker process managed by the executor was unexpectedly "
  614. "terminated. This could be caused by a segmentation fault "
  615. "while calling the function or by an excessive memory usage "
  616. "causing the Operating System to kill the worker.\n"
  617. f"{exit_codes}\n"
  618. "Detailed tracebacks of the workers should have been printed "
  619. "to stderr in the executor process if faulthandler was not "
  620. "disabled."
  621. )
  622. self.thread_wakeup.clear()
  623. return result_item, is_broken, bpe
  624. def process_result_item(self, result_item):
  625. # Process the received a result_item. This can be either the PID of a
  626. # worker that exited gracefully or a _ResultItem
  627. if isinstance(result_item, int):
  628. # Clean shutdown of a worker using its PID, either on request
  629. # by the executor.shutdown method or by the timeout of the worker
  630. # itself: we should not mark the executor as broken.
  631. with self.processes_management_lock:
  632. p = self.processes.pop(result_item, None)
  633. # p can be None if the executor is concurrently shutting down.
  634. if p is not None:
  635. p._worker_exit_lock.release()
  636. mp.util.debug(
  637. f"joining {p.name} when processing {p.pid} as result_item"
  638. )
  639. p.join()
  640. del p
  641. # Make sure the executor have the right number of worker, even if a
  642. # worker timeout while some jobs were submitted. If some work is
  643. # pending or there is less processes than running items, we need to
  644. # start a new Process and raise a warning.
  645. n_pending = len(self.pending_work_items)
  646. n_running = len(self.running_work_items)
  647. if n_pending - n_running > 0 or n_running > len(self.processes):
  648. executor = self.executor_reference()
  649. if (
  650. executor is not None
  651. and len(self.processes) < executor._max_workers
  652. ):
  653. warnings.warn(
  654. "A worker stopped while some jobs were given to the "
  655. "executor. This can be caused by a too short worker "
  656. "timeout or by a memory leak.",
  657. UserWarning,
  658. )
  659. with executor._processes_management_lock:
  660. executor._adjust_process_count()
  661. executor = None
  662. else:
  663. # Received a _ResultItem so mark the future as completed.
  664. work_item = self.pending_work_items.pop(result_item.work_id, None)
  665. # work_item can be None if another process terminated (see above)
  666. if work_item is not None:
  667. if result_item.exception:
  668. work_item.future.set_exception(result_item.exception)
  669. else:
  670. work_item.future.set_result(result_item.result)
  671. self.running_work_items.remove(result_item.work_id)
  672. def is_shutting_down(self):
  673. # Check whether we should start shutting down the executor.
  674. executor = self.executor_reference()
  675. # No more work items can be added if:
  676. # - The interpreter is shutting down OR
  677. # - The executor that owns this thread is not broken AND
  678. # * The executor that owns this worker has been collected OR
  679. # * The executor that owns this worker has been shutdown.
  680. # If the executor is broken, it should be detected in the next loop.
  681. return _global_shutdown or (
  682. (executor is None or self.executor_flags.shutdown)
  683. and not self.executor_flags.broken
  684. )
  685. def terminate_broken(self, bpe):
  686. # Terminate the executor because it is in a broken state. The bpe
  687. # argument can be used to display more information on the error that
  688. # lead the executor into becoming broken.
  689. # Mark the process pool broken so that submits fail right now.
  690. self.executor_flags.flag_as_broken(bpe)
  691. # Mark pending tasks as failed.
  692. for work_item in self.pending_work_items.values():
  693. work_item.future.set_exception(bpe)
  694. # Delete references to object. See issue16284
  695. del work_item
  696. self.pending_work_items.clear()
  697. # Terminate remaining workers forcibly: the queues or their
  698. # locks may be in a dirty state and block forever.
  699. self.kill_workers(reason="broken executor")
  700. # clean up resources
  701. self.join_executor_internals()
  702. def flag_executor_shutting_down(self):
  703. # Flag the executor as shutting down and cancel remaining tasks if
  704. # requested as early as possible if it is not gc-ed yet.
  705. self.executor_flags.flag_as_shutting_down()
  706. # Cancel pending work items if requested.
  707. if self.executor_flags.kill_workers:
  708. while self.pending_work_items:
  709. _, work_item = self.pending_work_items.popitem()
  710. work_item.future.set_exception(
  711. ShutdownExecutorError(
  712. "The Executor was shutdown with `kill_workers=True` "
  713. "before this job could complete."
  714. )
  715. )
  716. del work_item
  717. # Kill the remaining worker forcibly to no waste time joining them
  718. self.kill_workers(reason="executor shutting down")
  719. def kill_workers(self, reason=""):
  720. # Terminate the remaining workers using SIGKILL. This function also
  721. # terminates descendant workers of the children in case there is some
  722. # nested parallelism.
  723. while self.processes:
  724. _, p = self.processes.popitem()
  725. mp.util.debug(f"terminate process {p.name}, reason: {reason}")
  726. try:
  727. kill_process_tree(p)
  728. except ProcessLookupError: # pragma: no cover
  729. pass
  730. def shutdown_workers(self):
  731. # shutdown all workers in self.processes
  732. # Create a list to avoid RuntimeError due to concurrent modification of
  733. # processes. nb_children_alive is thus an upper bound. Also release the
  734. # processes' _worker_exit_lock to accelerate the shutdown procedure, as
  735. # there is no need for hand-shake here.
  736. with self.processes_management_lock:
  737. n_children_to_stop = 0
  738. for p in list(self.processes.values()):
  739. mp.util.debug(f"releasing worker exit lock on {p.name}")
  740. p._worker_exit_lock.release()
  741. n_children_to_stop += 1
  742. mp.util.debug(f"found {n_children_to_stop} processes to stop")
  743. # Send the right number of sentinels, to make sure all children are
  744. # properly terminated. Do it with a mechanism that avoid hanging on
  745. # Full queue when all workers have already been shutdown.
  746. n_sentinels_sent = 0
  747. cooldown_time = 0.001
  748. while (
  749. n_sentinels_sent < n_children_to_stop
  750. and self.get_n_children_alive() > 0
  751. ):
  752. for _ in range(n_children_to_stop - n_sentinels_sent):
  753. try:
  754. self.call_queue.put_nowait(None)
  755. n_sentinels_sent += 1
  756. except queue.Full as e:
  757. if cooldown_time > 5.0:
  758. mp.util.info(
  759. "failed to send all sentinels and exit with error."
  760. f"\ncall_queue size={self.call_queue._maxsize}; "
  761. f" full is {self.call_queue.full()}; "
  762. )
  763. raise e
  764. mp.util.info(
  765. "full call_queue prevented to send all sentinels at "
  766. "once, waiting..."
  767. )
  768. sleep(cooldown_time)
  769. cooldown_time *= 1.2
  770. break
  771. mp.util.debug(f"sent {n_sentinels_sent} sentinels to the call queue")
  772. def join_executor_internals(self):
  773. self.shutdown_workers()
  774. # Release the queue's resources as soon as possible. Flag the feeder
  775. # thread for clean exit to avoid having the crash detection thread flag
  776. # the Executor as broken during the shutdown. This is safe as either:
  777. # * We don't need to communicate with the workers anymore
  778. # * There is nothing left in the Queue buffer except None sentinels
  779. mp.util.debug("closing call_queue")
  780. self.call_queue.close()
  781. self.call_queue.join_thread()
  782. # Closing result_queue
  783. mp.util.debug("closing result_queue")
  784. self.result_queue.close()
  785. mp.util.debug("closing thread_wakeup")
  786. with self.shutdown_lock:
  787. self.thread_wakeup.close()
  788. # If .join() is not called on the created processes then
  789. # some ctx.Queue methods may deadlock on macOS.
  790. with self.processes_management_lock:
  791. mp.util.debug(f"joining {len(self.processes)} processes")
  792. n_joined_processes = 0
  793. while True:
  794. try:
  795. pid, p = self.processes.popitem()
  796. mp.util.debug(f"joining process {p.name} with pid {pid}")
  797. p.join()
  798. n_joined_processes += 1
  799. except KeyError:
  800. break
  801. mp.util.debug(
  802. "executor management thread clean shutdown of "
  803. f"{n_joined_processes} workers"
  804. )
  805. def get_n_children_alive(self):
  806. # This is an upper bound on the number of children alive.
  807. with self.processes_management_lock:
  808. return sum(p.is_alive() for p in list(self.processes.values()))
  809. _system_limits_checked = False
  810. _system_limited = None
  811. def _check_system_limits():
  812. global _system_limits_checked, _system_limited
  813. if _system_limits_checked and _system_limited:
  814. raise NotImplementedError(_system_limited)
  815. _system_limits_checked = True
  816. try:
  817. nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
  818. except (AttributeError, ValueError):
  819. # sysconf not available or setting not available
  820. return
  821. if nsems_max == -1:
  822. # undetermined limit, assume that limit is determined
  823. # by available memory only
  824. return
  825. if nsems_max >= 256:
  826. # minimum number of semaphores available
  827. # according to POSIX
  828. return
  829. _system_limited = (
  830. f"system provides too few semaphores ({nsems_max} available, "
  831. "256 necessary)"
  832. )
  833. raise NotImplementedError(_system_limited)
  834. def _chain_from_iterable_of_lists(iterable):
  835. """
  836. Specialized implementation of itertools.chain.from_iterable.
  837. Each item in *iterable* should be a list. This function is
  838. careful not to keep references to yielded objects.
  839. """
  840. for element in iterable:
  841. element.reverse()
  842. while element:
  843. yield element.pop()
  844. def _check_max_depth(context):
  845. # Limit the maxmal recursion level
  846. global _CURRENT_DEPTH
  847. if context.get_start_method() == "fork" and _CURRENT_DEPTH > 0:
  848. raise LokyRecursionError(
  849. "Could not spawn extra nested processes at depth superior to "
  850. "MAX_DEPTH=1. It is not possible to increase this limit when "
  851. "using the 'fork' start method."
  852. )
  853. if 0 < MAX_DEPTH and _CURRENT_DEPTH + 1 > MAX_DEPTH:
  854. raise LokyRecursionError(
  855. "Could not spawn extra nested processes at depth superior to "
  856. f"MAX_DEPTH={MAX_DEPTH}. If this is intendend, you can change "
  857. "this limit with the LOKY_MAX_DEPTH environment variable."
  858. )
  859. class LokyRecursionError(RuntimeError):
  860. """A process tries to spawn too many levels of nested processes."""
  861. class BrokenProcessPool(_BPPException):
  862. """
  863. Raised when the executor is broken while a future was in the running state.
  864. The cause can an error raised when unpickling the task in the worker
  865. process or when unpickling the result value in the parent process. It can
  866. also be caused by a worker process being terminated unexpectedly.
  867. """
  868. class TerminatedWorkerError(BrokenProcessPool):
  869. """
  870. Raised when a process in a ProcessPoolExecutor terminated abruptly
  871. while a future was in the running state.
  872. """
  873. # Alias for backward compat (for code written for loky 1.1.4 and earlier). Do
  874. # not use in new code.
  875. BrokenExecutor = BrokenProcessPool
  876. class ShutdownExecutorError(RuntimeError):
  877. """
  878. Raised when a ProcessPoolExecutor is shutdown while a future was in the
  879. running or pending state.
  880. """
  881. class ProcessPoolExecutor(Executor):
  882. _at_exit = None
  883. def __init__(
  884. self,
  885. max_workers=None,
  886. job_reducers=None,
  887. result_reducers=None,
  888. timeout=None,
  889. context=None,
  890. initializer=None,
  891. initargs=(),
  892. env=None,
  893. ):
  894. """Initializes a new ProcessPoolExecutor instance.
  895. Args:
  896. max_workers: int, optional (default: cpu_count())
  897. The maximum number of processes that can be used to execute the
  898. given calls. If None or not given then as many worker processes
  899. will be created as the number of CPUs the current process
  900. can use.
  901. job_reducers, result_reducers: dict(type: reducer_func)
  902. Custom reducer for pickling the jobs and the results from the
  903. Executor. If only `job_reducers` is provided, `result_reducer`
  904. will use the same reducers
  905. timeout: int, optional (default: None)
  906. Idle workers exit after timeout seconds. If a new job is
  907. submitted after the timeout, the executor will start enough
  908. new Python processes to make sure the pool of workers is full.
  909. context: A multiprocessing context to launch the workers. This
  910. object should provide SimpleQueue, Queue and Process.
  911. initializer: An callable used to initialize worker processes.
  912. initargs: A tuple of arguments to pass to the initializer.
  913. env: A dict of environment variable to overwrite in the child
  914. process. The environment variables are set before any module is
  915. loaded. Note that this only works with the loky context.
  916. """
  917. _check_system_limits()
  918. if max_workers is None:
  919. self._max_workers = cpu_count()
  920. else:
  921. if max_workers <= 0:
  922. raise ValueError("max_workers must be greater than 0")
  923. self._max_workers = max_workers
  924. if (
  925. sys.platform == "win32"
  926. and self._max_workers > _MAX_WINDOWS_WORKERS
  927. ):
  928. warnings.warn(
  929. f"On Windows, max_workers cannot exceed {_MAX_WINDOWS_WORKERS} "
  930. "due to limitations of the operating system."
  931. )
  932. self._max_workers = _MAX_WINDOWS_WORKERS
  933. if context is None:
  934. context = get_context()
  935. self._context = context
  936. self._env = env
  937. self._initializer, self._initargs = _prepare_initializer(
  938. initializer, initargs
  939. )
  940. _check_max_depth(self._context)
  941. if result_reducers is None:
  942. result_reducers = job_reducers
  943. # Timeout
  944. self._timeout = timeout
  945. # Management thread
  946. self._executor_manager_thread = None
  947. # Map of pids to processes
  948. self._processes = {}
  949. # Internal variables of the ProcessPoolExecutor
  950. self._processes = {}
  951. self._queue_count = 0
  952. self._pending_work_items = {}
  953. self._running_work_items = []
  954. self._work_ids = queue.Queue()
  955. self._processes_management_lock = self._context.Lock()
  956. self._executor_manager_thread = None
  957. self._shutdown_lock = threading.Lock()
  958. # _ThreadWakeup is a communication channel used to interrupt the wait
  959. # of the main loop of executor_manager_thread from another thread (e.g.
  960. # when calling executor.submit or executor.shutdown). We do not use the
  961. # _result_queue to send wakeup signals to the executor_manager_thread
  962. # as it could result in a deadlock if a worker process dies with the
  963. # _result_queue write lock still acquired.
  964. #
  965. # _shutdown_lock must be locked to access _ThreadWakeup.wakeup.
  966. self._executor_manager_thread_wakeup = _ThreadWakeup()
  967. # Flag to hold the state of the Executor. This permits to introspect
  968. # the Executor state even once it has been garbage collected.
  969. self._flags = _ExecutorFlags(self._shutdown_lock)
  970. # Finally setup the queues for interprocess communication
  971. self._setup_queues(job_reducers, result_reducers)
  972. mp.util.debug("ProcessPoolExecutor is setup")
  973. def _setup_queues(self, job_reducers, result_reducers, queue_size=None):
  974. # Make the call queue slightly larger than the number of processes to
  975. # prevent the worker processes from idling. But don't make it too big
  976. # because futures in the call queue cannot be cancelled.
  977. if queue_size is None:
  978. queue_size = 2 * self._max_workers + EXTRA_QUEUED_CALLS
  979. self._call_queue = _SafeQueue(
  980. max_size=queue_size,
  981. pending_work_items=self._pending_work_items,
  982. running_work_items=self._running_work_items,
  983. thread_wakeup=self._executor_manager_thread_wakeup,
  984. shutdown_lock=self._shutdown_lock,
  985. reducers=job_reducers,
  986. ctx=self._context,
  987. )
  988. # Killed worker processes can produce spurious "broken pipe"
  989. # tracebacks in the queue's own worker thread. But we detect killed
  990. # processes anyway, so silence the tracebacks.
  991. self._call_queue._ignore_epipe = True
  992. self._result_queue = SimpleQueue(
  993. reducers=result_reducers, ctx=self._context
  994. )
  995. def _start_executor_manager_thread(self):
  996. if self._executor_manager_thread is None:
  997. mp.util.debug("_start_executor_manager_thread called")
  998. # Start the processes so that their sentinels are known.
  999. self._executor_manager_thread = _ExecutorManagerThread(self)
  1000. self._executor_manager_thread.start()
  1001. # register this executor in a mechanism that ensures it will wakeup
  1002. # when the interpreter is exiting.
  1003. _threads_wakeups[self._executor_manager_thread] = (
  1004. self._shutdown_lock,
  1005. self._executor_manager_thread_wakeup,
  1006. )
  1007. global process_pool_executor_at_exit
  1008. if process_pool_executor_at_exit is None:
  1009. # Ensure that the _python_exit function will be called before
  1010. # the multiprocessing.Queue._close finalizers which have an
  1011. # exitpriority of 10.
  1012. if sys.version_info < (3, 9):
  1013. process_pool_executor_at_exit = mp.util.Finalize(
  1014. None, _python_exit, exitpriority=20
  1015. )
  1016. else:
  1017. process_pool_executor_at_exit = threading._register_atexit(
  1018. _python_exit
  1019. )
  1020. def _adjust_process_count(self):
  1021. while len(self._processes) < self._max_workers:
  1022. worker_exit_lock = self._context.BoundedSemaphore(1)
  1023. args = (
  1024. self._call_queue,
  1025. self._result_queue,
  1026. self._initializer,
  1027. self._initargs,
  1028. self._processes_management_lock,
  1029. self._timeout,
  1030. worker_exit_lock,
  1031. _CURRENT_DEPTH + 1,
  1032. )
  1033. worker_exit_lock.acquire()
  1034. try:
  1035. # Try to spawn the process with some environment variable to
  1036. # overwrite but it only works with the loky context for now.
  1037. p = self._context.Process(
  1038. target=_process_worker, args=args, env=self._env
  1039. )
  1040. except TypeError:
  1041. p = self._context.Process(target=_process_worker, args=args)
  1042. p._worker_exit_lock = worker_exit_lock
  1043. p.start()
  1044. self._processes[p.pid] = p
  1045. mp.util.debug(
  1046. f"Adjusted process count to {self._max_workers}: "
  1047. f"{[(p.name, pid) for pid, p in self._processes.items()]}"
  1048. )
  1049. def _ensure_executor_running(self):
  1050. """ensures all workers and management thread are running"""
  1051. with self._processes_management_lock:
  1052. if len(self._processes) != self._max_workers:
  1053. self._adjust_process_count()
  1054. self._start_executor_manager_thread()
  1055. def submit(self, fn, *args, **kwargs):
  1056. with self._flags.shutdown_lock:
  1057. if self._flags.broken is not None:
  1058. raise self._flags.broken
  1059. if self._flags.shutdown:
  1060. raise ShutdownExecutorError(
  1061. "cannot schedule new futures after shutdown"
  1062. )
  1063. # Cannot submit a new calls once the interpreter is shutting down.
  1064. # This check avoids spawning new processes at exit.
  1065. if _global_shutdown:
  1066. raise RuntimeError(
  1067. "cannot schedule new futures after interpreter shutdown"
  1068. )
  1069. f = Future()
  1070. w = _WorkItem(f, fn, args, kwargs)
  1071. self._pending_work_items[self._queue_count] = w
  1072. self._work_ids.put(self._queue_count)
  1073. self._queue_count += 1
  1074. # Wake up queue management thread
  1075. self._executor_manager_thread_wakeup.wakeup()
  1076. self._ensure_executor_running()
  1077. return f
  1078. submit.__doc__ = Executor.submit.__doc__
  1079. def map(self, fn, *iterables, **kwargs):
  1080. """Returns an iterator equivalent to map(fn, iter).
  1081. Args:
  1082. fn: A callable that will take as many arguments as there are
  1083. passed iterables.
  1084. timeout: The maximum number of seconds to wait. If None, then there
  1085. is no limit on the wait time.
  1086. chunksize: If greater than one, the iterables will be chopped into
  1087. chunks of size chunksize and submitted to the process pool.
  1088. If set to one, the items in the list will be sent one at a
  1089. time.
  1090. Returns:
  1091. An iterator equivalent to: map(func, *iterables) but the calls may
  1092. be evaluated out-of-order.
  1093. Raises:
  1094. TimeoutError: If the entire result iterator could not be generated
  1095. before the given timeout.
  1096. Exception: If fn(*args) raises for any values.
  1097. """
  1098. timeout = kwargs.get("timeout", None)
  1099. chunksize = kwargs.get("chunksize", 1)
  1100. if chunksize < 1:
  1101. raise ValueError("chunksize must be >= 1.")
  1102. results = super().map(
  1103. partial(_process_chunk, fn),
  1104. _get_chunks(chunksize, *iterables),
  1105. timeout=timeout,
  1106. )
  1107. return _chain_from_iterable_of_lists(results)
  1108. def shutdown(self, wait=True, kill_workers=False):
  1109. mp.util.debug(f"shutting down executor {self}")
  1110. self._flags.flag_as_shutting_down(kill_workers)
  1111. executor_manager_thread = self._executor_manager_thread
  1112. executor_manager_thread_wakeup = self._executor_manager_thread_wakeup
  1113. if executor_manager_thread_wakeup is not None:
  1114. # Wake up queue management thread
  1115. with self._shutdown_lock:
  1116. self._executor_manager_thread_wakeup.wakeup()
  1117. if executor_manager_thread is not None and wait:
  1118. # This locks avoids concurrent join if the interpreter
  1119. # is shutting down.
  1120. with _global_shutdown_lock:
  1121. executor_manager_thread.join()
  1122. _threads_wakeups.pop(executor_manager_thread, None)
  1123. # To reduce the risk of opening too many files, remove references to
  1124. # objects that use file descriptors.
  1125. self._executor_manager_thread = None
  1126. self._executor_manager_thread_wakeup = None
  1127. self._call_queue = None
  1128. self._result_queue = None
  1129. self._processes_management_lock = None
  1130. shutdown.__doc__ = Executor.shutdown.__doc__