blob: 2e7100bc3529d4b44b99562e1ef89658edc380b1 [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
Antoine Pitrou27be5da2011-04-12 17:48:46 +020083 continue
Antoine Pitrouc13d4542011-03-26 19:29:44 +010084 executor = executor_reference()
85 # Exit if:
86 # - The interpreter is shutting down OR
87 # - The executor that owns the worker has been collected OR
88 # - The executor that owns the worker has been shutdown.
89 if _shutdown or executor is None or executor._shutdown:
90 # Notice other workers
91 work_queue.put(None)
92 return
93 del executor
Florent Xicluna04842a82011-11-11 20:05:50 +010094 except BaseException:
Brian Quinlan81c4d362010-09-18 22:35:02 +000095 _base.LOGGER.critical('Exception in worker', exc_info=True)
96
Antoine Pitrou63ff4132017-11-04 11:05:49 +010097
98class BrokenThreadPool(_base.BrokenExecutor):
99 """
100 Raised when a worker thread in a ThreadPoolExecutor failed initializing.
101 """
102
103
Brian Quinlan81c4d362010-09-18 22:35:02 +0000104class ThreadPoolExecutor(_base.Executor):
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700105
106 # Used to assign unique thread names when thread_name_prefix is not supplied.
107 _counter = itertools.count().__next__
108
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100109 def __init__(self, max_workers=None, thread_name_prefix='',
110 initializer=None, initargs=()):
Brian Quinlan81c4d362010-09-18 22:35:02 +0000111 """Initializes a new ThreadPoolExecutor instance.
112
113 Args:
114 max_workers: The maximum number of threads that can be used to
115 execute the given calls.
Gregory P. Smith50abe872016-08-07 10:19:20 -0700116 thread_name_prefix: An optional name prefix to give our threads.
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100117 initializer: An callable used to initialize worker threads.
118 initargs: A tuple of arguments to pass to the initializer.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000119 """
Guido van Rossumcfd46612014-09-02 10:39:18 -0700120 if max_workers is None:
121 # Use this number because ThreadPoolExecutor is often
122 # used to overlap I/O instead of CPU work.
123 max_workers = (os.cpu_count() or 1) * 5
Brian Quinlan20efceb2014-05-17 13:51:10 -0700124 if max_workers <= 0:
125 raise ValueError("max_workers must be greater than 0")
126
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100127 if initializer is not None and not callable(initializer):
128 raise TypeError("initializer must be a callable")
129
Brian Quinlan81c4d362010-09-18 22:35:02 +0000130 self._max_workers = max_workers
131 self._work_queue = queue.Queue()
132 self._threads = set()
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100133 self._broken = False
Brian Quinlan81c4d362010-09-18 22:35:02 +0000134 self._shutdown = False
135 self._shutdown_lock = threading.Lock()
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700136 self._thread_name_prefix = (thread_name_prefix or
137 ("ThreadPoolExecutor-%d" % self._counter()))
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100138 self._initializer = initializer
139 self._initargs = initargs
Brian Quinlan81c4d362010-09-18 22:35:02 +0000140
141 def submit(self, fn, *args, **kwargs):
142 with self._shutdown_lock:
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100143 if self._broken:
144 raise BrokenThreadPool(self._broken)
145
Brian Quinlan81c4d362010-09-18 22:35:02 +0000146 if self._shutdown:
147 raise RuntimeError('cannot schedule new futures after shutdown')
148
149 f = _base.Future()
150 w = _WorkItem(f, fn, args, kwargs)
151
152 self._work_queue.put(w)
153 self._adjust_thread_count()
154 return f
155 submit.__doc__ = _base.Executor.submit.__doc__
156
157 def _adjust_thread_count(self):
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100158 # When the executor gets lost, the weakref callback will wake up
159 # the worker threads.
160 def weakref_cb(_, q=self._work_queue):
161 q.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000162 # TODO(bquinlan): Should avoid creating new threads if there are more
163 # idle threads than items in the work queue.
Gregory P. Smith50abe872016-08-07 10:19:20 -0700164 num_threads = len(self._threads)
165 if num_threads < self._max_workers:
166 thread_name = '%s_%d' % (self._thread_name_prefix or self,
167 num_threads)
168 t = threading.Thread(name=thread_name, target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100169 args=(weakref.ref(self, weakref_cb),
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100170 self._work_queue,
171 self._initializer,
172 self._initargs))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000173 t.daemon = True
174 t.start()
175 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100176 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000177
Antoine Pitrou63ff4132017-11-04 11:05:49 +0100178 def _initializer_failed(self):
179 with self._shutdown_lock:
180 self._broken = ('A thread initializer failed, the thread pool '
181 'is not usable anymore')
182 # Drain work queue and mark pending futures failed
183 while True:
184 try:
185 work_item = self._work_queue.get_nowait()
186 except queue.Empty:
187 break
188 if work_item is not None:
189 work_item.future.set_exception(BrokenThreadPool(self._broken))
190
Brian Quinlan81c4d362010-09-18 22:35:02 +0000191 def shutdown(self, wait=True):
192 with self._shutdown_lock:
193 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100194 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000195 if wait:
196 for t in self._threads:
197 t.join()
198 shutdown.__doc__ = _base.Executor.shutdown.__doc__