process.py 31 KB

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