blob: ad6b4c20b56681946b787be946bd87bad08734e1 [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
16# Workers are created as daemon threads. This is done to allow the interpreter
17# to exit when there are still idle threads in a ThreadPoolExecutor's thread
18# pool (i.e. shutdown() was not called). However, allowing workers to die with
19# the interpreter has two undesirable properties:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -070020# - The workers would still be running during interpreter shutdown,
Brian Quinlan81c4d362010-09-18 22:35:02 +000021# meaning that they would fail in unpredictable ways.
22# - The workers could be killed while evaluating a work item, which could
23# be bad if the callable being evaluated has external side-effects e.g.
24# writing to a file.
25#
26# To work around this problem, an exit handler is installed which tells the
27# workers to exit when their work queues are empty and then waits until the
28# threads finish.
29
Antoine Pitrouc13d4542011-03-26 19:29:44 +010030_threads_queues = weakref.WeakKeyDictionary()
Brian Quinlan81c4d362010-09-18 22:35:02 +000031_shutdown = False
32
33def _python_exit():
34 global _shutdown
35 _shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +010036 items = list(_threads_queues.items())
37 for t, q in items:
38 q.put(None)
39 for t, q in items:
40 t.join()
Brian Quinlan81c4d362010-09-18 22:35:02 +000041
42atexit.register(_python_exit)
43
Antoine Pitrou63ff4132017-11-04 11:05:49 +010044
Brian Quinlan81c4d362010-09-18 22:35:02 +000045class _WorkItem(object):
46 def __init__(self, future, fn, args, kwargs):
47 self.future = future
48 self.fn = fn
49 self.args = args
50 self.kwargs = kwargs
51
52 def run(self):
53 if not self.future.set_running_or_notify_cancel():
54 return
55
56 try:
57 result = self.fn(*self.args, **self.kwargs)
Victor Stinnerbc613152017-08-22 16:50:42 +020058 except BaseException as exc:
59 self.future.set_exception(exc)
60 # Break a reference cycle with the exception 'exc'
61 self = None
Brian Quinlan81c4d362010-09-18 22:35:02 +000062 else:
63 self.future.set_result(result)
64
Antoine Pitrou63ff4132017-11-04 11:05:49 +010065
66def _worker(executor_reference, work_queue, initializer, initargs):
67 if initializer is not None:
68 try:
69 initializer(*initargs)
70 except BaseException:
71 _base.LOGGER.critical('Exception in initializer:', exc_info=True)
72 executor = executor_reference()
73 if executor is not None:
74 executor._initializer_failed()
75 return
Brian Quinlan81c4d362010-09-18 22:35:02 +000076 try:
77 while True:
Antoine Pitrou27be5da2011-04-12 17:48:46 +020078 work_item = work_queue.get(block=True)
79 if work_item is not None:
80 work_item.run()
Andrew Svetlov6b973742012-11-03 15:36:01 +020081 # Delete references to object. See issue16284
82 del work_item
Sean904e34d2019-05-22 14:29:58 -070083
84 # attempt to increment idle count
85 executor = executor_reference()
86 if executor is not None:
87 executor._idle_semaphore.release()
88 del executor
Antoine Pitrou27be5da2011-04-12 17:48:46 +020089 continue
Sean904e34d2019-05-22 14:29:58 -070090
Antoine Pitrouc13d4542011-03-26 19:29:44 +010091 executor = executor_reference()
92 # Exit if:
93 # - The interpreter is shutting down OR
94 # - The executor that owns the worker has been collected OR
95 # - The executor that owns the worker has been shutdown.
96 if _shutdown or executor is None or executor._shutdown:
Mark Nemecc4b695f2018-04-10 18:23:14 +010097 # Flag the executor as shutting down as early as possible if it
98 # is not gc-ed yet.
99 if executor is not None:
100 executor._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100101 # Notice other workers
102 work_queue.put(None)
103 return
104 del executor
Florent Xicluna04842a82011-11-11 20:05:50 +0100105 except BaseException:
Brian Quinlan81c4d362010-09-18 22:35:02 +0000106 _base.LOGGER.critical('Exception in worker', exc_info=True)
107
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100108
109class BrokenThreadPool(_base.BrokenExecutor):
110 """
111 Raised when a worker thread in a ThreadPoolExecutor failed initializing.
112 """
113
114
Brian Quinlan81c4d362010-09-18 22:35:02 +0000115class ThreadPoolExecutor(_base.Executor):
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700116
117 # Used to assign unique thread names when thread_name_prefix is not supplied.
118 _counter = itertools.count().__next__
119
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100120 def __init__(self, max_workers=None, thread_name_prefix='',
121 initializer=None, initargs=()):
Brian Quinlan81c4d362010-09-18 22:35:02 +0000122 """Initializes a new ThreadPoolExecutor instance.
123
124 Args:
125 max_workers: The maximum number of threads that can be used to
126 execute the given calls.
Gregory P. Smith50abe872016-08-07 10:19:20 -0700127 thread_name_prefix: An optional name prefix to give our threads.
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100128 initializer: An callable used to initialize worker threads.
129 initargs: A tuple of arguments to pass to the initializer.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000130 """
Guido van Rossumcfd46612014-09-02 10:39:18 -0700131 if max_workers is None:
132 # Use this number because ThreadPoolExecutor is often
133 # used to overlap I/O instead of CPU work.
134 max_workers = (os.cpu_count() or 1) * 5
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 Storchaka42a139e2019-04-01 09:16:35 +0300153 def submit(*args, **kwargs):
154 if len(args) >= 2:
155 self, fn, *args = args
156 elif not args:
157 raise TypeError("descriptor 'submit' of 'ThreadPoolExecutor' object "
158 "needs an argument")
159 elif 'fn' in kwargs:
160 fn = kwargs.pop('fn')
161 self, *args = args
162 import warnings
163 warnings.warn("Passing 'fn' as keyword argument is deprecated",
164 DeprecationWarning, stacklevel=2)
165 else:
166 raise TypeError('submit expected at least 1 positional argument, '
167 'got %d' % (len(args)-1))
168
Brian Quinlan81c4d362010-09-18 22:35:02 +0000169 with self._shutdown_lock:
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100170 if self._broken:
171 raise BrokenThreadPool(self._broken)
172
Brian Quinlan81c4d362010-09-18 22:35:02 +0000173 if self._shutdown:
174 raise RuntimeError('cannot schedule new futures after shutdown')
Mark Nemecc4b695f2018-04-10 18:23:14 +0100175 if _shutdown:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +0200176 raise RuntimeError('cannot schedule new futures after '
Mark Nemecc4b695f2018-04-10 18:23:14 +0100177 'interpreter shutdown')
Brian Quinlan81c4d362010-09-18 22:35:02 +0000178
179 f = _base.Future()
180 w = _WorkItem(f, fn, args, kwargs)
181
182 self._work_queue.put(w)
183 self._adjust_thread_count()
184 return f
Serhiy Storchakad53cf992019-05-06 22:40:27 +0300185 submit.__text_signature__ = _base.Executor.submit.__text_signature__
Brian Quinlan81c4d362010-09-18 22:35:02 +0000186 submit.__doc__ = _base.Executor.submit.__doc__
187
188 def _adjust_thread_count(self):
Sean904e34d2019-05-22 14:29:58 -0700189 # if idle threads are available, don't spin new threads
190 if self._idle_semaphore.acquire(timeout=0):
191 return
192
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100193 # When the executor gets lost, the weakref callback will wake up
194 # the worker threads.
195 def weakref_cb(_, q=self._work_queue):
196 q.put(None)
Sean904e34d2019-05-22 14:29:58 -0700197
Gregory P. Smith50abe872016-08-07 10:19:20 -0700198 num_threads = len(self._threads)
199 if num_threads < self._max_workers:
200 thread_name = '%s_%d' % (self._thread_name_prefix or self,
201 num_threads)
202 t = threading.Thread(name=thread_name, target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100203 args=(weakref.ref(self, weakref_cb),
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100204 self._work_queue,
205 self._initializer,
206 self._initargs))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000207 t.daemon = True
208 t.start()
209 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100210 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000211
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100212 def _initializer_failed(self):
213 with self._shutdown_lock:
214 self._broken = ('A thread initializer failed, the thread pool '
215 'is not usable anymore')
216 # Drain work queue and mark pending futures failed
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.set_exception(BrokenThreadPool(self._broken))
224
Brian Quinlan81c4d362010-09-18 22:35:02 +0000225 def shutdown(self, wait=True):
226 with self._shutdown_lock:
227 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100228 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000229 if wait:
230 for t in self._threads:
231 t.join()
232 shutdown.__doc__ = _base.Executor.shutdown.__doc__