process.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Implements ProcessPoolExecutor.
  4. The follow diagram and text describe the data-flow through the system:
  5. |======================= In-process =====================|== Out-of-process ==|
  6. +----------+ +----------+ +--------+ +-----------+ +---------+
  7. | | => | Work Ids | => | | => | Call Q | => | |
  8. | | +----------+ | | +-----------+ | |
  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 atexit
  40. import os
  41. from concurrent.futures import _base
  42. import queue
  43. from queue import Full
  44. import multiprocessing
  45. from multiprocessing import SimpleQueue
  46. from multiprocessing.connection import wait
  47. import threading
  48. import weakref
  49. from functools import partial
  50. import itertools
  51. import traceback
  52. # Workers are created as daemon threads and processes. This is done to allow the
  53. # interpreter to exit when there are still idle processes in a
  54. # ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
  55. # allowing workers to die with the interpreter has two undesirable properties:
  56. # - The workers would still be running during interpretor shutdown,
  57. # meaning that they would fail in unpredictable ways.
  58. # - The workers could be killed while evaluating a work item, which could
  59. # be bad if the callable being evaluated has external side-effects e.g.
  60. # writing to a file.
  61. #
  62. # To work around this problem, an exit handler is installed which tells the
  63. # workers to exit when their work queues are empty and then waits until the
  64. # threads/processes finish.
  65. _threads_queues = weakref.WeakKeyDictionary()
  66. _shutdown = False
  67. def _python_exit():
  68. global _shutdown
  69. _shutdown = True
  70. items = list(_threads_queues.items())
  71. for t, q in items:
  72. q.put(None)
  73. for t, q in items:
  74. t.join()
  75. # Controls how many more calls than processes will be queued in the call queue.
  76. # A smaller number will mean that processes spend more time idle waiting for
  77. # work while a larger number will make Future.cancel() succeed less frequently
  78. # (Futures in the call queue cannot be cancelled).
  79. EXTRA_QUEUED_CALLS = 1
  80. # Hack to embed stringification of remote traceback in local traceback
  81. class _RemoteTraceback(Exception):
  82. def __init__(self, tb):
  83. self.tb = tb
  84. def __str__(self):
  85. return self.tb
  86. class _ExceptionWithTraceback:
  87. def __init__(self, exc, tb):
  88. tb = traceback.format_exception(type(exc), exc, tb)
  89. tb = ''.join(tb)
  90. self.exc = exc
  91. self.tb = '\n"""\n%s"""' % tb
  92. def __reduce__(self):
  93. return _rebuild_exc, (self.exc, self.tb)
  94. def _rebuild_exc(exc, tb):
  95. exc.__cause__ = _RemoteTraceback(tb)
  96. return exc
  97. class _WorkItem(object):
  98. def __init__(self, future, fn, args, kwargs):
  99. self.future = future
  100. self.fn = fn
  101. self.args = args
  102. self.kwargs = kwargs
  103. class _ResultItem(object):
  104. def __init__(self, work_id, exception=None, result=None):
  105. self.work_id = work_id
  106. self.exception = exception
  107. self.result = result
  108. class _CallItem(object):
  109. def __init__(self, work_id, fn, args, kwargs):
  110. self.work_id = work_id
  111. self.fn = fn
  112. self.args = args
  113. self.kwargs = kwargs
  114. def _get_chunks(*iterables, chunksize):
  115. """ Iterates over zip()ed iterables in chunks. """
  116. it = zip(*iterables)
  117. while True:
  118. chunk = tuple(itertools.islice(it, chunksize))
  119. if not chunk:
  120. return
  121. yield chunk
  122. def _process_chunk(fn, chunk):
  123. """ Processes a chunk of an iterable passed to map.
  124. Runs the function passed to map() on a chunk of the
  125. iterable passed to map.
  126. This function is run in a separate process.
  127. """
  128. return [fn(*args) for args in chunk]
  129. def _process_worker(call_queue, result_queue):
  130. """Evaluates calls from call_queue and places the results in result_queue.
  131. This worker is run in a separate process.
  132. Args:
  133. call_queue: A multiprocessing.Queue of _CallItems that will be read and
  134. evaluated by the worker.
  135. result_queue: A multiprocessing.Queue of _ResultItems that will written
  136. to by the worker.
  137. shutdown: A multiprocessing.Event that will be set as a signal to the
  138. worker that it should exit when call_queue is empty.
  139. """
  140. while True:
  141. call_item = call_queue.get(block=True)
  142. if call_item is None:
  143. # Wake up queue management thread
  144. result_queue.put(os.getpid())
  145. return
  146. try:
  147. r = call_item.fn(*call_item.args, **call_item.kwargs)
  148. except BaseException as e:
  149. exc = _ExceptionWithTraceback(e, e.__traceback__)
  150. result_queue.put(_ResultItem(call_item.work_id, exception=exc))
  151. else:
  152. result_queue.put(_ResultItem(call_item.work_id,
  153. result=r))
  154. def _add_call_item_to_queue(pending_work_items,
  155. work_ids,
  156. call_queue):
  157. """Fills call_queue with _WorkItems from pending_work_items.
  158. This function never blocks.
  159. Args:
  160. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  161. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  162. work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
  163. are consumed and the corresponding _WorkItems from
  164. pending_work_items are transformed into _CallItems and put in
  165. call_queue.
  166. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  167. derived from _WorkItems.
  168. """
  169. while True:
  170. if call_queue.full():
  171. return
  172. try:
  173. work_id = work_ids.get(block=False)
  174. except queue.Empty:
  175. return
  176. else:
  177. work_item = pending_work_items[work_id]
  178. if work_item.future.set_running_or_notify_cancel():
  179. call_queue.put(_CallItem(work_id,
  180. work_item.fn,
  181. work_item.args,
  182. work_item.kwargs),
  183. block=True)
  184. else:
  185. del pending_work_items[work_id]
  186. continue
  187. def _queue_management_worker(executor_reference,
  188. processes,
  189. pending_work_items,
  190. work_ids_queue,
  191. call_queue,
  192. result_queue):
  193. """Manages the communication between this process and the worker processes.
  194. This function is run in a local thread.
  195. Args:
  196. executor_reference: A weakref.ref to the ProcessPoolExecutor that owns
  197. this thread. Used to determine if the ProcessPoolExecutor has been
  198. garbage collected and that this function can exit.
  199. process: A list of the multiprocessing.Process instances used as
  200. workers.
  201. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  202. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  203. work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]).
  204. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  205. derived from _WorkItems for processing by the process workers.
  206. result_queue: A multiprocessing.Queue of _ResultItems generated by the
  207. process workers.
  208. """
  209. executor = None
  210. def shutting_down():
  211. return _shutdown or executor is None or executor._shutdown_thread
  212. def shutdown_worker():
  213. # This is an upper bound
  214. nb_children_alive = sum(p.is_alive() for p in processes.values())
  215. for i in range(0, nb_children_alive):
  216. call_queue.put_nowait(None)
  217. # Release the queue's resources as soon as possible.
  218. call_queue.close()
  219. # If .join() is not called on the created processes then
  220. # some multiprocessing.Queue methods may deadlock on Mac OS X.
  221. for p in processes.values():
  222. p.join()
  223. reader = result_queue._reader
  224. while True:
  225. _add_call_item_to_queue(pending_work_items,
  226. work_ids_queue,
  227. call_queue)
  228. sentinels = [p.sentinel for p in processes.values()]
  229. assert sentinels
  230. ready = wait([reader] + sentinels)
  231. if reader in ready:
  232. result_item = reader.recv()
  233. else:
  234. # Mark the process pool broken so that submits fail right now.
  235. executor = executor_reference()
  236. if executor is not None:
  237. executor._broken = True
  238. executor._shutdown_thread = True
  239. executor = None
  240. # All futures in flight must be marked failed
  241. for work_id, work_item in pending_work_items.items():
  242. work_item.future.set_exception(
  243. BrokenProcessPool(
  244. "A process in the process pool was "
  245. "terminated abruptly while the future was "
  246. "running or pending."
  247. ))
  248. # Delete references to object. See issue16284
  249. del work_item
  250. pending_work_items.clear()
  251. # Terminate remaining workers forcibly: the queues or their
  252. # locks may be in a dirty state and block forever.
  253. for p in processes.values():
  254. p.terminate()
  255. shutdown_worker()
  256. return
  257. if isinstance(result_item, int):
  258. # Clean shutdown of a worker using its PID
  259. # (avoids marking the executor broken)
  260. assert shutting_down()
  261. p = processes.pop(result_item)
  262. p.join()
  263. if not processes:
  264. shutdown_worker()
  265. return
  266. elif result_item is not None:
  267. work_item = pending_work_items.pop(result_item.work_id, None)
  268. # work_item can be None if another process terminated (see above)
  269. if work_item is not None:
  270. if result_item.exception:
  271. work_item.future.set_exception(result_item.exception)
  272. else:
  273. work_item.future.set_result(result_item.result)
  274. # Delete references to object. See issue16284
  275. del work_item
  276. # Check whether we should start shutting down.
  277. executor = executor_reference()
  278. # No more work items can be added if:
  279. # - The interpreter is shutting down OR
  280. # - The executor that owns this worker has been collected OR
  281. # - The executor that owns this worker has been shutdown.
  282. if shutting_down():
  283. try:
  284. # Since no new work items can be added, it is safe to shutdown
  285. # this thread if there are no pending work items.
  286. if not pending_work_items:
  287. shutdown_worker()
  288. return
  289. except Full:
  290. # This is not a problem: we will eventually be woken up (in
  291. # result_queue.get()) and be able to send a sentinel again.
  292. pass
  293. executor = None
  294. _system_limits_checked = False
  295. _system_limited = None
  296. def _check_system_limits():
  297. global _system_limits_checked, _system_limited
  298. if _system_limits_checked:
  299. if _system_limited:
  300. raise NotImplementedError(_system_limited)
  301. _system_limits_checked = True
  302. try:
  303. nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
  304. except (AttributeError, ValueError):
  305. # sysconf not available or setting not available
  306. return
  307. if nsems_max == -1:
  308. # indetermined limit, assume that limit is determined
  309. # by available memory only
  310. return
  311. if nsems_max >= 256:
  312. # minimum number of semaphores available
  313. # according to POSIX
  314. return
  315. _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max
  316. raise NotImplementedError(_system_limited)
  317. class BrokenProcessPool(RuntimeError):
  318. """
  319. Raised when a process in a ProcessPoolExecutor terminated abruptly
  320. while a future was in the running state.
  321. """
  322. class ProcessPoolExecutor(_base.Executor):
  323. def __init__(self, max_workers=None):
  324. """Initializes a new ProcessPoolExecutor instance.
  325. Args:
  326. max_workers: The maximum number of processes that can be used to
  327. execute the given calls. If None or not given then as many
  328. worker processes will be created as the machine has processors.
  329. """
  330. _check_system_limits()
  331. if max_workers is None:
  332. self._max_workers = os.cpu_count() or 1
  333. else:
  334. if max_workers <= 0:
  335. raise ValueError("max_workers must be greater than 0")
  336. self._max_workers = max_workers
  337. # Make the call queue slightly larger than the number of processes to
  338. # prevent the worker processes from idling. But don't make it too big
  339. # because futures in the call queue cannot be cancelled.
  340. self._call_queue = multiprocessing.Queue(self._max_workers +
  341. EXTRA_QUEUED_CALLS)
  342. # Killed worker processes can produce spurious "broken pipe"
  343. # tracebacks in the queue's own worker thread. But we detect killed
  344. # processes anyway, so silence the tracebacks.
  345. self._call_queue._ignore_epipe = True
  346. self._result_queue = SimpleQueue()
  347. self._work_ids = queue.Queue()
  348. self._queue_management_thread = None
  349. # Map of pids to processes
  350. self._processes = {}
  351. # Shutdown is a two-step process.
  352. self._shutdown_thread = False
  353. self._shutdown_lock = threading.Lock()
  354. self._broken = False
  355. self._queue_count = 0
  356. self._pending_work_items = {}
  357. def _start_queue_management_thread(self):
  358. # When the executor gets lost, the weakref callback will wake up
  359. # the queue management thread.
  360. def weakref_cb(_, q=self._result_queue):
  361. q.put(None)
  362. if self._queue_management_thread is None:
  363. # Start the processes so that their sentinels are known.
  364. self._adjust_process_count()
  365. self._queue_management_thread = threading.Thread(
  366. target=_queue_management_worker,
  367. args=(weakref.ref(self, weakref_cb),
  368. self._processes,
  369. self._pending_work_items,
  370. self._work_ids,
  371. self._call_queue,
  372. self._result_queue))
  373. self._queue_management_thread.daemon = True
  374. self._queue_management_thread.start()
  375. _threads_queues[self._queue_management_thread] = self._result_queue
  376. def _adjust_process_count(self):
  377. for _ in range(len(self._processes), self._max_workers):
  378. p = multiprocessing.Process(
  379. target=_process_worker,
  380. args=(self._call_queue,
  381. self._result_queue))
  382. p.start()
  383. self._processes[p.pid] = p
  384. def submit(self, fn, *args, **kwargs):
  385. with self._shutdown_lock:
  386. if self._broken:
  387. raise BrokenProcessPool('A child process terminated '
  388. 'abruptly, the process pool is not usable anymore')
  389. if self._shutdown_thread:
  390. raise RuntimeError('cannot schedule new futures after shutdown')
  391. f = _base.Future()
  392. w = _WorkItem(f, fn, args, kwargs)
  393. self._pending_work_items[self._queue_count] = w
  394. self._work_ids.put(self._queue_count)
  395. self._queue_count += 1
  396. # Wake up queue management thread
  397. self._result_queue.put(None)
  398. self._start_queue_management_thread()
  399. return f
  400. submit.__doc__ = _base.Executor.submit.__doc__
  401. def map(self, fn, *iterables, timeout=None, chunksize=1):
  402. """Returns an iterator equivalent to map(fn, iter).
  403. Args:
  404. fn: A callable that will take as many arguments as there are
  405. passed iterables.
  406. timeout: The maximum number of seconds to wait. If None, then there
  407. is no limit on the wait time.
  408. chunksize: If greater than one, the iterables will be chopped into
  409. chunks of size chunksize and submitted to the process pool.
  410. If set to one, the items in the list will be sent one at a time.
  411. Returns:
  412. An iterator equivalent to: map(func, *iterables) but the calls may
  413. be evaluated out-of-order.
  414. Raises:
  415. TimeoutError: If the entire result iterator could not be generated
  416. before the given timeout.
  417. Exception: If fn(*args) raises for any values.
  418. """
  419. if chunksize < 1:
  420. raise ValueError("chunksize must be >= 1.")
  421. results = super().map(partial(_process_chunk, fn),
  422. _get_chunks(*iterables, chunksize=chunksize),
  423. timeout=timeout)
  424. return itertools.chain.from_iterable(results)
  425. def shutdown(self, wait=True):
  426. with self._shutdown_lock:
  427. self._shutdown_thread = True
  428. if self._queue_management_thread:
  429. # Wake up queue management thread
  430. self._result_queue.put(None)
  431. if wait:
  432. self._queue_management_thread.join()
  433. # To reduce the risk of opening too many files, remove references to
  434. # objects that use file descriptors.
  435. self._queue_management_thread = None
  436. self._call_queue = None
  437. self._result_queue = None
  438. self._processes = None
  439. shutdown.__doc__ = _base.Executor.shutdown.__doc__
  440. atexit.register(_python_exit)