process.py 15 KB

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