process.py 33 KB

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