Advertisement
Guest User

Untitled

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