You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

130 lines
4.4 KiB

  1. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Implements ThreadPoolExecutor."""
  4. __author__ = 'Brian Quinlan (brian@sweetapp.com)'
  5. import atexit
  6. from concurrent.futures import _base
  7. import queue
  8. import threading
  9. import weakref
  10. # Workers are created as daemon threads. This is done to allow the interpreter
  11. # to exit when there are still idle threads in a ThreadPoolExecutor's thread
  12. # pool (i.e. shutdown() was not called). However, allowing workers to die with
  13. # the interpreter has two undesirable properties:
  14. # - The workers would still be running during interpretor shutdown,
  15. # meaning that they would fail in unpredictable ways.
  16. # - The workers could be killed while evaluating a work item, which could
  17. # be bad if the callable being evaluated has external side-effects e.g.
  18. # writing to a file.
  19. #
  20. # To work around this problem, an exit handler is installed which tells the
  21. # workers to exit when their work queues are empty and then waits until the
  22. # threads finish.
  23. _threads_queues = weakref.WeakKeyDictionary()
  24. _shutdown = False
  25. def _python_exit():
  26. global _shutdown
  27. _shutdown = True
  28. items = list(_threads_queues.items())
  29. for t, q in items:
  30. q.put(None)
  31. for t, q in items:
  32. t.join()
  33. atexit.register(_python_exit)
  34. class _WorkItem(object):
  35. def __init__(self, future, fn, args, kwargs):
  36. self.future = future
  37. self.fn = fn
  38. self.args = args
  39. self.kwargs = kwargs
  40. def run(self):
  41. if not self.future.set_running_or_notify_cancel():
  42. return
  43. try:
  44. result = self.fn(*self.args, **self.kwargs)
  45. except BaseException as e:
  46. self.future.set_exception(e)
  47. else:
  48. self.future.set_result(result)
  49. def _worker(executor_reference, work_queue):
  50. try:
  51. while True:
  52. work_item = work_queue.get(block=True)
  53. if work_item is not None:
  54. work_item.run()
  55. continue
  56. executor = executor_reference()
  57. # Exit if:
  58. # - The interpreter is shutting down OR
  59. # - The executor that owns the worker has been collected OR
  60. # - The executor that owns the worker has been shutdown.
  61. if _shutdown or executor is None or executor._shutdown:
  62. # Notice other workers
  63. work_queue.put(None)
  64. return
  65. del executor
  66. except BaseException as e:
  67. _base.LOGGER.critical('Exception in worker', exc_info=True)
  68. class ThreadPoolExecutor(_base.Executor):
  69. def __init__(self, max_workers):
  70. """Initializes a new ThreadPoolExecutor instance.
  71. Args:
  72. max_workers: The maximum number of threads that can be used to
  73. execute the given calls.
  74. """
  75. self._max_workers = max_workers
  76. self._work_queue = queue.Queue()
  77. self._threads = set()
  78. self._shutdown = False
  79. self._shutdown_lock = threading.Lock()
  80. def submit(self, fn, *args, **kwargs):
  81. with self._shutdown_lock:
  82. if self._shutdown:
  83. raise RuntimeError('cannot schedule new futures after shutdown')
  84. f = _base.Future()
  85. w = _WorkItem(f, fn, args, kwargs)
  86. self._work_queue.put(w)
  87. self._adjust_thread_count()
  88. return f
  89. submit.__doc__ = _base.Executor.submit.__doc__
  90. def _adjust_thread_count(self):
  91. # When the executor gets lost, the weakref callback will wake up
  92. # the worker threads.
  93. def weakref_cb(_, q=self._work_queue):
  94. q.put(None)
  95. # TODO(bquinlan): Should avoid creating new threads if there are more
  96. # idle threads than items in the work queue.
  97. if len(self._threads) < self._max_workers:
  98. t = threading.Thread(target=_worker,
  99. args=(weakref.ref(self, weakref_cb),
  100. self._work_queue))
  101. t.daemon = True
  102. t.start()
  103. self._threads.add(t)
  104. _threads_queues[t] = self._work_queue
  105. def shutdown(self, wait=True):
  106. with self._shutdown_lock:
  107. self._shutdown = True
  108. self._work_queue.put(None)
  109. if wait:
  110. for t in self._threads:
  111. t.join()
  112. shutdown.__doc__ = _base.Executor.shutdown.__doc__