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. 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. _threads_queues = weakref.WeakKeyDictionary()
  64. _shutdown = False
  65. def _python_exit():
  66. global _shutdown
  67. _shutdown = True
  68. items = list(_threads_queues.items())
  69. for t, q in items:
  70. q.put(None)
  71. for t, q in items:
  72. t.join()
  73. # Controls how many more calls than processes will be queued in the call queue.
  74. # A smaller number will mean that processes spend more time idle waiting for
  75. # work while a larger number will make Future.cancel() succeed less frequently
  76. # (Futures in the call queue cannot be cancelled).
  77. EXTRA_QUEUED_CALLS = 1
  78. class _WorkItem(object):
  79. def __init__(self, future, fn, args, kwargs):
  80. self.future = future
  81. self.fn = fn
  82. self.args = args
  83. self.kwargs = kwargs
  84. class _ResultItem(object):
  85. def __init__(self, work_id, exception=None, result=None):
  86. self.work_id = work_id
  87. self.exception = exception
  88. self.result = result
  89. class _CallItem(object):
  90. def __init__(self, work_id, fn, args, kwargs):
  91. self.work_id = work_id
  92. self.fn = fn
  93. self.args = args
  94. self.kwargs = kwargs
  95. def _process_worker(call_queue, result_queue):
  96. """Evaluates calls from call_queue and places the results in result_queue.
  97. This worker is run in a separate process.
  98. Args:
  99. call_queue: A multiprocessing.Queue of _CallItems that will be read and
  100. evaluated by the worker.
  101. result_queue: A multiprocessing.Queue of _ResultItems that will written
  102. to by the worker.
  103. shutdown: A multiprocessing.Event that will be set as a signal to the
  104. worker that it should exit when call_queue is empty.
  105. """
  106. while True:
  107. call_item = call_queue.get(block=True)
  108. if call_item is None:
  109. # Wake up queue management thread
  110. result_queue.put(None)
  111. return
  112. try:
  113. r = call_item.fn(*call_item.args, **call_item.kwargs)
  114. except BaseException:
  115. e = sys.exc_info()[1]
  116. result_queue.put(_ResultItem(call_item.work_id,
  117. exception=e))
  118. else:
  119. result_queue.put(_ResultItem(call_item.work_id,
  120. result=r))
  121. def _add_call_item_to_queue(pending_work_items,
  122. work_ids,
  123. call_queue):
  124. """Fills call_queue with _WorkItems from pending_work_items.
  125. This function never blocks.
  126. Args:
  127. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  128. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  129. work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids
  130. are consumed and the corresponding _WorkItems from
  131. pending_work_items are transformed into _CallItems and put in
  132. call_queue.
  133. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  134. derived from _WorkItems.
  135. """
  136. while True:
  137. if call_queue.full():
  138. return
  139. try:
  140. work_id = work_ids.get(block=False)
  141. except queue.Empty:
  142. return
  143. else:
  144. work_item = pending_work_items[work_id]
  145. if work_item.future.set_running_or_notify_cancel():
  146. call_queue.put(_CallItem(work_id,
  147. work_item.fn,
  148. work_item.args,
  149. work_item.kwargs),
  150. block=True)
  151. else:
  152. del pending_work_items[work_id]
  153. continue
  154. def _queue_management_worker(executor_reference,
  155. processes,
  156. pending_work_items,
  157. work_ids_queue,
  158. call_queue,
  159. result_queue):
  160. """Manages the communication between this process and the worker processes.
  161. This function is run in a local thread.
  162. Args:
  163. executor_reference: A weakref.ref to the ProcessPoolExecutor that owns
  164. this thread. Used to determine if the ProcessPoolExecutor has been
  165. garbage collected and that this function can exit.
  166. process: A list of the multiprocessing.Process instances used as
  167. workers.
  168. pending_work_items: A dict mapping work ids to _WorkItems e.g.
  169. {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
  170. work_ids_queue: A queue.Queue of work ids e.g. Queue([5, 6, ...]).
  171. call_queue: A multiprocessing.Queue that will be filled with _CallItems
  172. derived from _WorkItems for processing by the process workers.
  173. result_queue: A multiprocessing.Queue of _ResultItems generated by the
  174. process workers.
  175. """
  176. nb_shutdown_processes = [0]
  177. def shutdown_one_process():
  178. """Tell a worker to terminate, which will in turn wake us again"""
  179. call_queue.put(None)
  180. nb_shutdown_processes[0] += 1
  181. while True:
  182. _add_call_item_to_queue(pending_work_items,
  183. work_ids_queue,
  184. call_queue)
  185. result_item = result_queue.get(block=True)
  186. if result_item is not None:
  187. work_item = pending_work_items[result_item.work_id]
  188. del pending_work_items[result_item.work_id]
  189. if result_item.exception:
  190. work_item.future.set_exception(result_item.exception)
  191. else:
  192. work_item.future.set_result(result_item.result)
  193. # Check whether we should start shutting down.
  194. executor = executor_reference()
  195. # No more work items can be added if:
  196. # - The interpreter is shutting down OR
  197. # - The executor that owns this worker has been collected OR
  198. # - The executor that owns this worker has been shutdown.
  199. if _shutdown or executor is None or executor._shutdown_thread:
  200. # Since no new work items can be added, it is safe to shutdown
  201. # this thread if there are no pending work items.
  202. if not pending_work_items:
  203. while nb_shutdown_processes[0] < len(processes):
  204. shutdown_one_process()
  205. # If .join() is not called on the created processes then
  206. # some multiprocessing.Queue methods may deadlock on Mac OS
  207. # X.
  208. for p in processes:
  209. p.join()
  210. call_queue.close()
  211. return
  212. del executor
  213. _system_limits_checked = False
  214. _system_limited = None
  215. def _check_system_limits():
  216. global _system_limits_checked, _system_limited
  217. if _system_limits_checked:
  218. if _system_limited:
  219. raise NotImplementedError(_system_limited)
  220. _system_limits_checked = True
  221. try:
  222. import os
  223. nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
  224. except (AttributeError, ValueError):
  225. # sysconf not available or setting not available
  226. return
  227. if nsems_max == -1:
  228. # indetermine limit, assume that limit is determined
  229. # by available memory only
  230. return
  231. if nsems_max >= 256:
  232. # minimum number of semaphores available
  233. # according to POSIX
  234. return
  235. _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max
  236. raise NotImplementedError(_system_limited)
  237. class ProcessPoolExecutor(_base.Executor):
  238. def __init__(self, max_workers=None):
  239. """Initializes a new ProcessPoolExecutor instance.
  240. Args:
  241. max_workers: The maximum number of processes that can be used to
  242. execute the given calls. If None or not given then as many
  243. worker processes will be created as the machine has processors.
  244. """
  245. _check_system_limits()
  246. if max_workers is None:
  247. self._max_workers = multiprocessing.cpu_count()
  248. else:
  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()
  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)