process.py 35 KB

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