process.py 34 KB

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