process.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 "Request Q"
  37. """
  38. from __future__ import with_statement
  39. import atexit
  40. import multiprocessing
  41. import threading
  42. import weakref
  43. import sys
  44. from concurrent.futures import _base
  45. try:
  46. import queue
  47. except ImportError:
  48. import Queue as queue
  49. __author__ = 'Brian Quinlan (brian@sweetapp.com)'
  50. # Workers are created as daemon threads and processes. This is done to allow the
  51. # interpreter to exit when there are still idle processes in a
  52. # ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
  53. # allowing workers to die with the interpreter has two undesirable properties:
  54. # - The workers would still be running during interpretor shutdown,
  55. # meaning that they would fail in unpredictable ways.
  56. # - The workers could be killed while evaluating a work item, which could
  57. # be bad if the callable being evaluated has external side-effects e.g.
  58. # writing to a file.
  59. #
  60. # To work around this problem, an exit handler is installed which tells the
  61. # workers to exit when their work queues are empty and then waits until the
  62. # threads/processes finish.
  63. _thread_references = set()
  64. _shutdown = False
  65. def _python_exit():
  66. global _shutdown
  67. _shutdown = True
  68. for thread_reference in _thread_references:
  69. thread = thread_reference()
  70. if thread is not None:
  71. thread.join()
  72. def _remove_dead_thread_references():
  73. """Remove inactive threads from _thread_references.
  74. Should be called periodically to prevent memory leaks in scenarios such as:
  75. >>> while True:
  76. >>> ... t = ThreadPoolExecutor(max_workers=5)
  77. >>> ... t.map(int, ['1', '2', '3', '4', '5'])
  78. """
  79. for thread_reference in set(_thread_references):
  80. if thread_reference() is None:
  81. _thread_references.discard(thread_reference)
  82. # Controls how many more calls than processes will be queued in the call queue.
  83. # A smaller number will mean that processes spend more time idle waiting for
  84. # work while a larger number will make Future.cancel() succeed less frequently
  85. # (Futures in the call queue cannot be cancelled).
  86. EXTRA_QUEUED_CALLS = 1
  87. class _WorkItem(object):
  88. def __init__(self, future, fn, args, kwargs):
  89. self.future = future
  90. self.fn = fn
  91. self.args = args
  92. self.kwargs = kwargs
  93. class _ResultItem(object):
  94. def __init__(self, work_id, exception=None, result=None):
  95. self.work_id = work_id
  96. self.exception = exception
  97. self.result = result
  98. class _CallItem(object):
  99. def __init__(self, work_id, fn, args, kwargs):
  100. self.work_id = work_id
  101. self.fn = fn
  102. self.args = args
  103. self.kwargs = kwargs
  104. def _process_worker(call_queue, result_queue, shutdown):
  105. """Evaluates calls from call_queue and places the results in result_queue.
  106. This worker is run in a seperate process.
  107. Args:
  108. call_queue: A multiprocessing.Queue of _CallItems that will be read and
  109. evaluated by the worker.
  110. result_queue: A multiprocessing.Queue of _ResultItems that will written
  111. to by the worker.
  112. shutdown: A multiprocessing.Event that will be set as a signal to the
  113. worker that it should exit when call_queue is empty.
  114. """
  115. while True:
  116. try:
  117. call_item = call_queue.get(block=True, timeout=0.1)
  118. except queue.Empty:
  119. if shutdown.is_set():
  120. return
  121. else:
  122. try:
  123. r = call_item.fn(*call_item.args, **call_item.kwargs)
  124. except BaseException:
  125. e = sys.exc_info()[1]
  126. result_queue.put(_ResultItem(call_item.work_id,
  127. exception=e))
  128. else:
  129. result_queue.put(_ResultItem(call_item.work_id,
  130. result=r))
  131. def _add_call_item_to_queue(pending_work_items,
  132. work_ids,
  133. call_queue):
  134. """Fills call_queue with _WorkItems from pending_work_items.
  135. This function never blocks.
  136. Args:
  137. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  138. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  139. work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
  140. are consumed and the corresponding _WorkItems from
  141. pending_work_items are transformed into _CallItems and put in
  142. call_queue.
  143. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  144. derived from _WorkItems.
  145. """
  146. while True:
  147. if call_queue.full():
  148. return
  149. try:
  150. work_id = work_ids.get(block=False)
  151. except queue.Empty:
  152. return
  153. else:
  154. work_item = pending_work_items[work_id]
  155. if work_item.future.set_running_or_notify_cancel():
  156. call_queue.put(_CallItem(work_id,
  157. work_item.fn,
  158. work_item.args,
  159. work_item.kwargs),
  160. block=True)
  161. else:
  162. del pending_work_items[work_id]
  163. continue
  164. def _queue_manangement_worker(executor_reference,
  165. processes,
  166. pending_work_items,
  167. work_ids_queue,
  168. call_queue,
  169. result_queue,
  170. shutdown_process_event):
  171. """Manages the communication between this process and the worker processes.
  172. This function is run in a local thread.
  173. Args:
  174. executor_reference: A weakref.ref to the ProcessPoolExecutor that owns
  175. this thread. Used to determine if the ProcessPoolExecutor has been
  176. garbage collected and that this function can exit.
  177. process: A list of the multiprocessing.Process instances used as
  178. workers.
  179. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  180. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  181. work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]).
  182. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  183. derived from _WorkItems for processing by the process workers.
  184. result_queue: A multiprocessing.Queue of _ResultItems generated by the
  185. process workers.
  186. shutdown_process_event: A multiprocessing.Event used to signal the
  187. process workers that they should exit when their work queue is
  188. empty.
  189. """
  190. while True:
  191. _add_call_item_to_queue(pending_work_items,
  192. work_ids_queue,
  193. call_queue)
  194. try:
  195. result_item = result_queue.get(block=True, timeout=0.1)
  196. except queue.Empty:
  197. executor = executor_reference()
  198. # No more work items can be added if:
  199. # - The interpreter is shutting down OR
  200. # - The executor that owns this worker has been collected OR
  201. # - The executor that owns this worker has been shutdown.
  202. if _shutdown or executor is None or executor._shutdown_thread:
  203. # Since no new work items can be added, it is safe to shutdown
  204. # this thread if there are no pending work items.
  205. if not pending_work_items:
  206. shutdown_process_event.set()
  207. # If .join() is not called on the created processes then
  208. # some multiprocessing.Queue methods may deadlock on Mac OS
  209. # X.
  210. for p in processes:
  211. p.join()
  212. return
  213. del executor
  214. else:
  215. work_item = pending_work_items[result_item.work_id]
  216. del pending_work_items[result_item.work_id]
  217. if result_item.exception:
  218. work_item.future.set_exception(result_item.exception)
  219. else:
  220. work_item.future.set_result(result_item.result)
  221. class ProcessPoolExecutor(_base.Executor):
  222. def __init__(self, max_workers=None):
  223. """Initializes a new ProcessPoolExecutor instance.
  224. Args:
  225. max_workers: The maximum number of processes that can be used to
  226. execute the given calls. If None or not given then as many
  227. worker processes will be created as the machine has processors.
  228. """
  229. _remove_dead_thread_references()
  230. if max_workers is None:
  231. self._max_workers = multiprocessing.cpu_count()
  232. else:
  233. self._max_workers = max_workers
  234. # Make the call queue slightly larger than the number of processes to
  235. # prevent the worker processes from idling. But don't make it too big
  236. # because futures in the call queue cannot be cancelled.
  237. self._call_queue = multiprocessing.Queue(self._max_workers +
  238. EXTRA_QUEUED_CALLS)
  239. self._result_queue = multiprocessing.Queue()
  240. self._work_ids = queue.Queue()
  241. self._queue_management_thread = None
  242. self._processes = set()
  243. # Shutdown is a two-step process.
  244. self._shutdown_thread = False
  245. self._shutdown_process_event = multiprocessing.Event()
  246. self._shutdown_lock = threading.Lock()
  247. self._queue_count = 0
  248. self._pending_work_items = {}
  249. def _start_queue_management_thread(self):
  250. if self._queue_management_thread is None:
  251. self._queue_management_thread = threading.Thread(
  252. target=_queue_manangement_worker,
  253. args=(weakref.ref(self),
  254. self._processes,
  255. self._pending_work_items,
  256. self._work_ids,
  257. self._call_queue,
  258. self._result_queue,
  259. self._shutdown_process_event))
  260. self._queue_management_thread.daemon = True
  261. self._queue_management_thread.start()
  262. _thread_references.add(weakref.ref(self._queue_management_thread))
  263. def _adjust_process_count(self):
  264. for _ in range(len(self._processes), self._max_workers):
  265. p = multiprocessing.Process(
  266. target=_process_worker,
  267. args=(self._call_queue,
  268. self._result_queue,
  269. self._shutdown_process_event))
  270. p.start()
  271. self._processes.add(p)
  272. def submit(self, fn, *args, **kwargs):
  273. with self._shutdown_lock:
  274. if self._shutdown_thread:
  275. raise RuntimeError('cannot schedule new futures after shutdown')
  276. f = _base.Future()
  277. w = _WorkItem(f, fn, args, kwargs)
  278. self._pending_work_items[self._queue_count] = w
  279. self._work_ids.put(self._queue_count)
  280. self._queue_count += 1
  281. self._start_queue_management_thread()
  282. self._adjust_process_count()
  283. return f
  284. submit.__doc__ = _base.Executor.submit.__doc__
  285. def shutdown(self, wait=True):
  286. with self._shutdown_lock:
  287. self._shutdown_thread = True
  288. if wait:
  289. if self._queue_management_thread:
  290. self._queue_management_thread.join()
  291. # To reduce the risk of openning too many files, remove references to
  292. # objects that use file descriptors.
  293. self._queue_management_thread = None
  294. self._call_queue = None
  295. self._result_queue = None
  296. self._shutdown_process_event = None
  297. self._processes = None
  298. shutdown.__doc__ = _base.Executor.shutdown.__doc__
  299. atexit.register(_python_exit)