blob: 2810b357bc1e17daa78129e427514463c5afded5 [file] [log] [blame]
Brian Quinlan81c4d362010-09-18 22:35:02 +00001# Copyright 2009 Brian Quinlan. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Implements ThreadPoolExecutor."""
5
6__author__ = 'Brian Quinlan (brian@sweetapp.com)'
7
8import atexit
9from concurrent.futures import _base
Gregory P. Smitha3d91b42017-06-21 23:41:13 -070010import itertools
Brian Quinlan81c4d362010-09-18 22:35:02 +000011import queue
12import threading
Batuhan Taşkaya03615562020-04-10 17:46:36 +030013import types
Brian Quinlan81c4d362010-09-18 22:35:02 +000014import weakref
Guido van Rossumcfd46612014-09-02 10:39:18 -070015import os
Brian Quinlan81c4d362010-09-18 22:35:02 +000016
Brian Quinlan81c4d362010-09-18 22:35:02 +000017
Antoine Pitrouc13d4542011-03-26 19:29:44 +010018_threads_queues = weakref.WeakKeyDictionary()
Brian Quinlan81c4d362010-09-18 22:35:02 +000019_shutdown = False
Brian Quinlan242c26f2019-06-28 11:54:52 -070020# Lock that ensures that new workers are not created while the interpreter is
21# shutting down. Must be held while mutating _threads_queues and _shutdown.
22_global_shutdown_lock = threading.Lock()
Brian Quinlan81c4d362010-09-18 22:35:02 +000023
24def _python_exit():
25 global _shutdown
Brian Quinlan242c26f2019-06-28 11:54:52 -070026 with _global_shutdown_lock:
27 _shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +010028 items = list(_threads_queues.items())
29 for t, q in items:
30 q.put(None)
31 for t, q in items:
32 t.join()
Brian Quinlan81c4d362010-09-18 22:35:02 +000033
Kyle Stanleyb61b8182020-03-27 15:31:22 -040034# Register for `_python_exit()` to be called just before joining all
35# non-daemon threads. This is used instead of `atexit.register()` for
36# compatibility with subinterpreters, which no longer support daemon threads.
37# See bpo-39812 for context.
38threading._register_atexit(_python_exit)
Brian Quinlan81c4d362010-09-18 22:35:02 +000039
Antoine Pitrou63ff4132017-11-04 11:05:49 +010040
Brian Quinlan81c4d362010-09-18 22:35:02 +000041class _WorkItem(object):
42 def __init__(self, future, fn, args, kwargs):
43 self.future = future
44 self.fn = fn
45 self.args = args
46 self.kwargs = kwargs
47
48 def run(self):
49 if not self.future.set_running_or_notify_cancel():
50 return
51
52 try:
53 result = self.fn(*self.args, **self.kwargs)
Victor Stinnerbc613152017-08-22 16:50:42 +020054 except BaseException as exc:
55 self.future.set_exception(exc)
56 # Break a reference cycle with the exception 'exc'
57 self = None
Brian Quinlan81c4d362010-09-18 22:35:02 +000058 else:
59 self.future.set_result(result)
60
Batuhan Taşkaya03615562020-04-10 17:46:36 +030061 __class_getitem__ = classmethod(types.GenericAlias)
62
Antoine Pitrou63ff4132017-11-04 11:05:49 +010063
64def _worker(executor_reference, work_queue, initializer, initargs):
65 if initializer is not None:
66 try:
67 initializer(*initargs)
68 except BaseException:
69 _base.LOGGER.critical('Exception in initializer:', exc_info=True)
70 executor = executor_reference()
71 if executor is not None:
72 executor._initializer_failed()
73 return
Brian Quinlan81c4d362010-09-18 22:35:02 +000074 try:
75 while True:
Antoine Pitrou27be5da2011-04-12 17:48:46 +020076 work_item = work_queue.get(block=True)
77 if work_item is not None:
78 work_item.run()
Andrew Svetlov6b973742012-11-03 15:36:01 +020079 # Delete references to object. See issue16284
80 del work_item
Sean904e34d2019-05-22 14:29:58 -070081
82 # attempt to increment idle count
83 executor = executor_reference()
84 if executor is not None:
85 executor._idle_semaphore.release()
86 del executor
Antoine Pitrou27be5da2011-04-12 17:48:46 +020087 continue
Sean904e34d2019-05-22 14:29:58 -070088
Antoine Pitrouc13d4542011-03-26 19:29:44 +010089 executor = executor_reference()
90 # Exit if:
91 # - The interpreter is shutting down OR
92 # - The executor that owns the worker has been collected OR
93 # - The executor that owns the worker has been shutdown.
94 if _shutdown or executor is None or executor._shutdown:
Mark Nemecc4b695f2018-04-10 18:23:14 +010095 # Flag the executor as shutting down as early as possible if it
96 # is not gc-ed yet.
97 if executor is not None:
98 executor._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +010099 # Notice other workers
100 work_queue.put(None)
101 return
102 del executor
Florent Xicluna04842a82011-11-11 20:05:50 +0100103 except BaseException:
Brian Quinlan81c4d362010-09-18 22:35:02 +0000104 _base.LOGGER.critical('Exception in worker', exc_info=True)
105
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100106
107class BrokenThreadPool(_base.BrokenExecutor):
108 """
109 Raised when a worker thread in a ThreadPoolExecutor failed initializing.
110 """
111
112
Brian Quinlan81c4d362010-09-18 22:35:02 +0000113class ThreadPoolExecutor(_base.Executor):
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700114
115 # Used to assign unique thread names when thread_name_prefix is not supplied.
116 _counter = itertools.count().__next__
117
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100118 def __init__(self, max_workers=None, thread_name_prefix='',
119 initializer=None, initargs=()):
Brian Quinlan81c4d362010-09-18 22:35:02 +0000120 """Initializes a new ThreadPoolExecutor instance.
121
122 Args:
123 max_workers: The maximum number of threads that can be used to
124 execute the given calls.
Gregory P. Smith50abe872016-08-07 10:19:20 -0700125 thread_name_prefix: An optional name prefix to give our threads.
ubordignon552ace72019-06-15 13:43:10 +0200126 initializer: A callable used to initialize worker threads.
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100127 initargs: A tuple of arguments to pass to the initializer.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000128 """
Guido van Rossumcfd46612014-09-02 10:39:18 -0700129 if max_workers is None:
Inada Naoki9a7e5b12019-05-28 21:02:52 +0900130 # ThreadPoolExecutor is often used to:
131 # * CPU bound task which releases GIL
132 # * I/O bound task (which releases GIL, of course)
133 #
134 # We use cpu_count + 4 for both types of tasks.
135 # But we limit it to 32 to avoid consuming surprisingly large resource
136 # on many core machine.
137 max_workers = min(32, (os.cpu_count() or 1) + 4)
Brian Quinlan20efceb2014-05-17 13:51:10 -0700138 if max_workers <= 0:
139 raise ValueError("max_workers must be greater than 0")
140
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100141 if initializer is not None and not callable(initializer):
142 raise TypeError("initializer must be a callable")
143
Brian Quinlan81c4d362010-09-18 22:35:02 +0000144 self._max_workers = max_workers
Antoine Pitrouab745042018-01-18 10:38:03 +0100145 self._work_queue = queue.SimpleQueue()
Sean904e34d2019-05-22 14:29:58 -0700146 self._idle_semaphore = threading.Semaphore(0)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000147 self._threads = set()
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100148 self._broken = False
Brian Quinlan81c4d362010-09-18 22:35:02 +0000149 self._shutdown = False
150 self._shutdown_lock = threading.Lock()
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700151 self._thread_name_prefix = (thread_name_prefix or
152 ("ThreadPoolExecutor-%d" % self._counter()))
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100153 self._initializer = initializer
154 self._initargs = initargs
Brian Quinlan81c4d362010-09-18 22:35:02 +0000155
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300156 def submit(self, fn, /, *args, **kwargs):
Brian Quinlan242c26f2019-06-28 11:54:52 -0700157 with self._shutdown_lock, _global_shutdown_lock:
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100158 if self._broken:
159 raise BrokenThreadPool(self._broken)
160
Brian Quinlan81c4d362010-09-18 22:35:02 +0000161 if self._shutdown:
162 raise RuntimeError('cannot schedule new futures after shutdown')
Mark Nemecc4b695f2018-04-10 18:23:14 +0100163 if _shutdown:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200164 raise RuntimeError('cannot schedule new futures after '
Mark Nemecc4b695f2018-04-10 18:23:14 +0100165 'interpreter shutdown')
Brian Quinlan81c4d362010-09-18 22:35:02 +0000166
167 f = _base.Future()
168 w = _WorkItem(f, fn, args, kwargs)
169
170 self._work_queue.put(w)
171 self._adjust_thread_count()
172 return f
173 submit.__doc__ = _base.Executor.submit.__doc__
174
175 def _adjust_thread_count(self):
Sean904e34d2019-05-22 14:29:58 -0700176 # if idle threads are available, don't spin new threads
177 if self._idle_semaphore.acquire(timeout=0):
178 return
179
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100180 # When the executor gets lost, the weakref callback will wake up
181 # the worker threads.
182 def weakref_cb(_, q=self._work_queue):
183 q.put(None)
Sean904e34d2019-05-22 14:29:58 -0700184
Gregory P. Smith50abe872016-08-07 10:19:20 -0700185 num_threads = len(self._threads)
186 if num_threads < self._max_workers:
187 thread_name = '%s_%d' % (self._thread_name_prefix or self,
188 num_threads)
189 t = threading.Thread(name=thread_name, target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100190 args=(weakref.ref(self, weakref_cb),
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100191 self._work_queue,
192 self._initializer,
193 self._initargs))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000194 t.start()
195 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100196 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000197
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100198 def _initializer_failed(self):
199 with self._shutdown_lock:
200 self._broken = ('A thread initializer failed, the thread pool '
201 'is not usable anymore')
202 # Drain work queue and mark pending futures failed
203 while True:
204 try:
205 work_item = self._work_queue.get_nowait()
206 except queue.Empty:
207 break
208 if work_item is not None:
209 work_item.future.set_exception(BrokenThreadPool(self._broken))
210
Kyle Stanley339fd462020-02-02 07:49:00 -0500211 def shutdown(self, wait=True, *, cancel_futures=False):
Brian Quinlan81c4d362010-09-18 22:35:02 +0000212 with self._shutdown_lock:
213 self._shutdown = True
Kyle Stanley339fd462020-02-02 07:49:00 -0500214 if cancel_futures:
215 # Drain all work items from the queue, and then cancel their
216 # associated futures.
217 while True:
218 try:
219 work_item = self._work_queue.get_nowait()
220 except queue.Empty:
221 break
222 if work_item is not None:
223 work_item.future.cancel()
224
225 # Send a wake-up to prevent threads calling
226 # _work_queue.get(block=True) from permanently blocking.
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100227 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000228 if wait:
229 for t in self._threads:
230 t.join()
231 shutdown.__doc__ = _base.Executor.shutdown.__doc__