blob: 2aa4e17d47fa7c3e11461d310fc933c593982d7c [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
13import weakref
Guido van Rossumcfd46612014-09-02 10:39:18 -070014import os
Brian Quinlan81c4d362010-09-18 22:35:02 +000015
Brian Quinlan81c4d362010-09-18 22:35:02 +000016
Antoine Pitrouc13d4542011-03-26 19:29:44 +010017_threads_queues = weakref.WeakKeyDictionary()
Brian Quinlan81c4d362010-09-18 22:35:02 +000018_shutdown = False
Brian Quinlan242c26f2019-06-28 11:54:52 -070019# Lock that ensures that new workers are not created while the interpreter is
20# shutting down. Must be held while mutating _threads_queues and _shutdown.
21_global_shutdown_lock = threading.Lock()
Brian Quinlan81c4d362010-09-18 22:35:02 +000022
23def _python_exit():
24 global _shutdown
Brian Quinlan242c26f2019-06-28 11:54:52 -070025 with _global_shutdown_lock:
26 _shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +010027 items = list(_threads_queues.items())
28 for t, q in items:
29 q.put(None)
30 for t, q in items:
31 t.join()
Brian Quinlan81c4d362010-09-18 22:35:02 +000032
Kyle Stanleyb61b8182020-03-27 15:31:22 -040033# Register for `_python_exit()` to be called just before joining all
34# non-daemon threads. This is used instead of `atexit.register()` for
35# compatibility with subinterpreters, which no longer support daemon threads.
36# See bpo-39812 for context.
37threading._register_atexit(_python_exit)
Brian Quinlan81c4d362010-09-18 22:35:02 +000038
Antoine Pitrou63ff4132017-11-04 11:05:49 +010039
Brian Quinlan81c4d362010-09-18 22:35:02 +000040class _WorkItem(object):
41 def __init__(self, future, fn, args, kwargs):
42 self.future = future
43 self.fn = fn
44 self.args = args
45 self.kwargs = kwargs
46
47 def run(self):
48 if not self.future.set_running_or_notify_cancel():
49 return
50
51 try:
52 result = self.fn(*self.args, **self.kwargs)
Victor Stinnerbc613152017-08-22 16:50:42 +020053 except BaseException as exc:
54 self.future.set_exception(exc)
55 # Break a reference cycle with the exception 'exc'
56 self = None
Brian Quinlan81c4d362010-09-18 22:35:02 +000057 else:
58 self.future.set_result(result)
59
Antoine Pitrou63ff4132017-11-04 11:05:49 +010060
61def _worker(executor_reference, work_queue, initializer, initargs):
62 if initializer is not None:
63 try:
64 initializer(*initargs)
65 except BaseException:
66 _base.LOGGER.critical('Exception in initializer:', exc_info=True)
67 executor = executor_reference()
68 if executor is not None:
69 executor._initializer_failed()
70 return
Brian Quinlan81c4d362010-09-18 22:35:02 +000071 try:
72 while True:
Antoine Pitrou27be5da2011-04-12 17:48:46 +020073 work_item = work_queue.get(block=True)
74 if work_item is not None:
75 work_item.run()
Andrew Svetlov6b973742012-11-03 15:36:01 +020076 # Delete references to object. See issue16284
77 del work_item
Sean904e34d2019-05-22 14:29:58 -070078
79 # attempt to increment idle count
80 executor = executor_reference()
81 if executor is not None:
82 executor._idle_semaphore.release()
83 del executor
Antoine Pitrou27be5da2011-04-12 17:48:46 +020084 continue
Sean904e34d2019-05-22 14:29:58 -070085
Antoine Pitrouc13d4542011-03-26 19:29:44 +010086 executor = executor_reference()
87 # Exit if:
88 # - The interpreter is shutting down OR
89 # - The executor that owns the worker has been collected OR
90 # - The executor that owns the worker has been shutdown.
91 if _shutdown or executor is None or executor._shutdown:
Mark Nemecc4b695f2018-04-10 18:23:14 +010092 # Flag the executor as shutting down as early as possible if it
93 # is not gc-ed yet.
94 if executor is not None:
95 executor._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +010096 # Notice other workers
97 work_queue.put(None)
98 return
99 del executor
Florent Xicluna04842a82011-11-11 20:05:50 +0100100 except BaseException:
Brian Quinlan81c4d362010-09-18 22:35:02 +0000101 _base.LOGGER.critical('Exception in worker', exc_info=True)
102
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100103
104class BrokenThreadPool(_base.BrokenExecutor):
105 """
106 Raised when a worker thread in a ThreadPoolExecutor failed initializing.
107 """
108
109
Brian Quinlan81c4d362010-09-18 22:35:02 +0000110class ThreadPoolExecutor(_base.Executor):
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700111
112 # Used to assign unique thread names when thread_name_prefix is not supplied.
113 _counter = itertools.count().__next__
114
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100115 def __init__(self, max_workers=None, thread_name_prefix='',
116 initializer=None, initargs=()):
Brian Quinlan81c4d362010-09-18 22:35:02 +0000117 """Initializes a new ThreadPoolExecutor instance.
118
119 Args:
120 max_workers: The maximum number of threads that can be used to
121 execute the given calls.
Gregory P. Smith50abe872016-08-07 10:19:20 -0700122 thread_name_prefix: An optional name prefix to give our threads.
ubordignon552ace72019-06-15 13:43:10 +0200123 initializer: A callable used to initialize worker threads.
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100124 initargs: A tuple of arguments to pass to the initializer.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000125 """
Guido van Rossumcfd46612014-09-02 10:39:18 -0700126 if max_workers is None:
Inada Naoki9a7e5b12019-05-28 21:02:52 +0900127 # ThreadPoolExecutor is often used to:
128 # * CPU bound task which releases GIL
129 # * I/O bound task (which releases GIL, of course)
130 #
131 # We use cpu_count + 4 for both types of tasks.
132 # But we limit it to 32 to avoid consuming surprisingly large resource
133 # on many core machine.
134 max_workers = min(32, (os.cpu_count() or 1) + 4)
Brian Quinlan20efceb2014-05-17 13:51:10 -0700135 if max_workers <= 0:
136 raise ValueError("max_workers must be greater than 0")
137
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100138 if initializer is not None and not callable(initializer):
139 raise TypeError("initializer must be a callable")
140
Brian Quinlan81c4d362010-09-18 22:35:02 +0000141 self._max_workers = max_workers
Antoine Pitrouab745042018-01-18 10:38:03 +0100142 self._work_queue = queue.SimpleQueue()
Sean904e34d2019-05-22 14:29:58 -0700143 self._idle_semaphore = threading.Semaphore(0)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000144 self._threads = set()
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100145 self._broken = False
Brian Quinlan81c4d362010-09-18 22:35:02 +0000146 self._shutdown = False
147 self._shutdown_lock = threading.Lock()
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700148 self._thread_name_prefix = (thread_name_prefix or
149 ("ThreadPoolExecutor-%d" % self._counter()))
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100150 self._initializer = initializer
151 self._initargs = initargs
Brian Quinlan81c4d362010-09-18 22:35:02 +0000152
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300153 def submit(self, fn, /, *args, **kwargs):
Brian Quinlan242c26f2019-06-28 11:54:52 -0700154 with self._shutdown_lock, _global_shutdown_lock:
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100155 if self._broken:
156 raise BrokenThreadPool(self._broken)
157
Brian Quinlan81c4d362010-09-18 22:35:02 +0000158 if self._shutdown:
159 raise RuntimeError('cannot schedule new futures after shutdown')
Mark Nemecc4b695f2018-04-10 18:23:14 +0100160 if _shutdown:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200161 raise RuntimeError('cannot schedule new futures after '
Mark Nemecc4b695f2018-04-10 18:23:14 +0100162 'interpreter shutdown')
Brian Quinlan81c4d362010-09-18 22:35:02 +0000163
164 f = _base.Future()
165 w = _WorkItem(f, fn, args, kwargs)
166
167 self._work_queue.put(w)
168 self._adjust_thread_count()
169 return f
170 submit.__doc__ = _base.Executor.submit.__doc__
171
172 def _adjust_thread_count(self):
Sean904e34d2019-05-22 14:29:58 -0700173 # if idle threads are available, don't spin new threads
174 if self._idle_semaphore.acquire(timeout=0):
175 return
176
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100177 # When the executor gets lost, the weakref callback will wake up
178 # the worker threads.
179 def weakref_cb(_, q=self._work_queue):
180 q.put(None)
Sean904e34d2019-05-22 14:29:58 -0700181
Gregory P. Smith50abe872016-08-07 10:19:20 -0700182 num_threads = len(self._threads)
183 if num_threads < self._max_workers:
184 thread_name = '%s_%d' % (self._thread_name_prefix or self,
185 num_threads)
186 t = threading.Thread(name=thread_name, target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100187 args=(weakref.ref(self, weakref_cb),
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100188 self._work_queue,
189 self._initializer,
190 self._initargs))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000191 t.start()
192 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100193 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000194
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100195 def _initializer_failed(self):
196 with self._shutdown_lock:
197 self._broken = ('A thread initializer failed, the thread pool '
198 'is not usable anymore')
199 # Drain work queue and mark pending futures failed
200 while True:
201 try:
202 work_item = self._work_queue.get_nowait()
203 except queue.Empty:
204 break
205 if work_item is not None:
206 work_item.future.set_exception(BrokenThreadPool(self._broken))
207
Kyle Stanley339fd462020-02-02 07:49:00 -0500208 def shutdown(self, wait=True, *, cancel_futures=False):
Brian Quinlan81c4d362010-09-18 22:35:02 +0000209 with self._shutdown_lock:
210 self._shutdown = True
Kyle Stanley339fd462020-02-02 07:49:00 -0500211 if cancel_futures:
212 # Drain all work items from the queue, and then cancel their
213 # associated futures.
214 while True:
215 try:
216 work_item = self._work_queue.get_nowait()
217 except queue.Empty:
218 break
219 if work_item is not None:
220 work_item.future.cancel()
221
222 # Send a wake-up to prevent threads calling
223 # _work_queue.get(block=True) from permanently blocking.
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100224 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000225 if wait:
226 for t in self._threads:
227 t.join()
228 shutdown.__doc__ = _base.Executor.shutdown.__doc__