thread.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. from concurrent.futures import _base
  6. import itertools
  7. import queue
  8. import threading
  9. import types
  10. import weakref
  11. import os
  12. _threads_queues = weakref.WeakKeyDictionary()
  13. _shutdown = False
  14. # Lock that ensures that new workers are not created while the interpreter is
  15. # shutting down. Must be held while mutating _threads_queues and _shutdown.
  16. _global_shutdown_lock = threading.Lock()
  17. def _python_exit():
  18. global _shutdown
  19. with _global_shutdown_lock:
  20. _shutdown = True
  21. items = list(_threads_queues.items())
  22. for t, q in items:
  23. q.put(None)
  24. for t, q in items:
  25. t.join()
  26. # Register for `_python_exit()` to be called just before joining all
  27. # non-daemon threads. This is used instead of `atexit.register()` for
  28. # compatibility with subinterpreters, which no longer support daemon threads.
  29. # See bpo-39812 for context.
  30. threading._register_atexit(_python_exit)
  31. # At fork, reinitialize the `_global_shutdown_lock` lock in the child process
  32. if hasattr(os, 'register_at_fork'):
  33. os.register_at_fork(before=_global_shutdown_lock.acquire,
  34. after_in_child=_global_shutdown_lock._at_fork_reinit,
  35. after_in_parent=_global_shutdown_lock.release)
  36. class _WorkItem:
  37. def __init__(self, future, fn, args, kwargs):
  38. self.future = future
  39. self.fn = fn
  40. self.args = args
  41. self.kwargs = kwargs
  42. def run(self):
  43. if not self.future.set_running_or_notify_cancel():
  44. return
  45. try:
  46. result = self.fn(*self.args, **self.kwargs)
  47. except BaseException as exc:
  48. self.future.set_exception(exc)
  49. # Break a reference cycle with the exception 'exc'
  50. self = None
  51. else:
  52. self.future.set_result(result)
  53. __class_getitem__ = classmethod(types.GenericAlias)
  54. def _worker(executor_reference, work_queue, initializer, initargs):
  55. if initializer is not None:
  56. try:
  57. initializer(*initargs)
  58. except BaseException:
  59. _base.LOGGER.critical('Exception in initializer:', exc_info=True)
  60. executor = executor_reference()
  61. if executor is not None:
  62. executor._initializer_failed()
  63. return
  64. try:
  65. while True:
  66. try:
  67. work_item = work_queue.get_nowait()
  68. except queue.Empty:
  69. # attempt to increment idle count if queue is empty
  70. executor = executor_reference()
  71. if executor is not None:
  72. executor._idle_semaphore.release()
  73. del executor
  74. work_item = work_queue.get(block=True)
  75. if work_item is not None:
  76. work_item.run()
  77. # Delete references to object. See GH-60488
  78. del work_item
  79. continue
  80. executor = executor_reference()
  81. # Exit if:
  82. # - The interpreter is shutting down OR
  83. # - The executor that owns the worker has been collected OR
  84. # - The executor that owns the worker has been shutdown.
  85. if _shutdown or executor is None or executor._shutdown:
  86. # Flag the executor as shutting down as early as possible if it
  87. # is not gc-ed yet.
  88. if executor is not None:
  89. executor._shutdown = True
  90. # Notice other workers
  91. work_queue.put(None)
  92. return
  93. del executor
  94. except BaseException:
  95. _base.LOGGER.critical('Exception in worker', exc_info=True)
  96. class BrokenThreadPool(_base.BrokenExecutor):
  97. """
  98. Raised when a worker thread in a ThreadPoolExecutor failed initializing.
  99. """
  100. class ThreadPoolExecutor(_base.Executor):
  101. # Used to assign unique thread names when thread_name_prefix is not supplied.
  102. _counter = itertools.count().__next__
  103. def __init__(self, max_workers=None, thread_name_prefix='',
  104. initializer=None, initargs=()):
  105. """Initializes a new ThreadPoolExecutor instance.
  106. Args:
  107. max_workers: The maximum number of threads that can be used to
  108. execute the given calls.
  109. thread_name_prefix: An optional name prefix to give our threads.
  110. initializer: A callable used to initialize worker threads.
  111. initargs: A tuple of arguments to pass to the initializer.
  112. """
  113. if max_workers is None:
  114. # ThreadPoolExecutor is often used to:
  115. # * CPU bound task which releases GIL
  116. # * I/O bound task (which releases GIL, of course)
  117. #
  118. # We use cpu_count + 4 for both types of tasks.
  119. # But we limit it to 32 to avoid consuming surprisingly large resource
  120. # on many core machine.
  121. max_workers = min(32, (os.cpu_count() or 1) + 4)
  122. if max_workers <= 0:
  123. raise ValueError("max_workers must be greater than 0")
  124. if initializer is not None and not callable(initializer):
  125. raise TypeError("initializer must be a callable")
  126. self._max_workers = max_workers
  127. self._work_queue = queue.SimpleQueue()
  128. self._idle_semaphore = threading.Semaphore(0)
  129. self._threads = set()
  130. self._broken = False
  131. self._shutdown = False
  132. self._shutdown_lock = threading.Lock()
  133. self._thread_name_prefix = (thread_name_prefix or
  134. ("ThreadPoolExecutor-%d" % self._counter()))
  135. self._initializer = initializer
  136. self._initargs = initargs
  137. def submit(self, fn, /, *args, **kwargs):
  138. with self._shutdown_lock, _global_shutdown_lock:
  139. if self._broken:
  140. raise BrokenThreadPool(self._broken)
  141. if self._shutdown:
  142. raise RuntimeError('cannot schedule new futures after shutdown')
  143. if _shutdown:
  144. raise RuntimeError('cannot schedule new futures after '
  145. 'interpreter shutdown')
  146. f = _base.Future()
  147. w = _WorkItem(f, fn, args, kwargs)
  148. self._work_queue.put(w)
  149. self._adjust_thread_count()
  150. return f
  151. submit.__doc__ = _base.Executor.submit.__doc__
  152. def _adjust_thread_count(self):
  153. # if idle threads are available, don't spin new threads
  154. if self._idle_semaphore.acquire(timeout=0):
  155. return
  156. # When the executor gets lost, the weakref callback will wake up
  157. # the worker threads.
  158. def weakref_cb(_, q=self._work_queue):
  159. q.put(None)
  160. num_threads = len(self._threads)
  161. if num_threads < self._max_workers:
  162. thread_name = '%s_%d' % (self._thread_name_prefix or self,
  163. num_threads)
  164. t = threading.Thread(name=thread_name, target=_worker,
  165. args=(weakref.ref(self, weakref_cb),
  166. self._work_queue,
  167. self._initializer,
  168. self._initargs))
  169. t.start()
  170. self._threads.add(t)
  171. _threads_queues[t] = self._work_queue
  172. def _initializer_failed(self):
  173. with self._shutdown_lock:
  174. self._broken = ('A thread initializer failed, the thread pool '
  175. 'is not usable anymore')
  176. # Drain work queue and mark pending futures failed
  177. while True:
  178. try:
  179. work_item = self._work_queue.get_nowait()
  180. except queue.Empty:
  181. break
  182. if work_item is not None:
  183. work_item.future.set_exception(BrokenThreadPool(self._broken))
  184. def shutdown(self, wait=True, *, cancel_futures=False):
  185. with self._shutdown_lock:
  186. self._shutdown = True
  187. if cancel_futures:
  188. # Drain all work items from the queue, and then cancel their
  189. # associated futures.
  190. while True:
  191. try:
  192. work_item = self._work_queue.get_nowait()
  193. except queue.Empty:
  194. break
  195. if work_item is not None:
  196. work_item.future.cancel()
  197. # Send a wake-up to prevent threads calling
  198. # _work_queue.get(block=True) from permanently blocking.
  199. self._work_queue.put(None)
  200. if wait:
  201. for t in self._threads:
  202. t.join()
  203. shutdown.__doc__ = _base.Executor.shutdown.__doc__