blob: 1f0a1d4b977f316cdd8fa65dc57b3e4afb8204dd [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
44class _WorkItem(object):
45 def __init__(self, future, fn, args, kwargs):
46 self.future = future
47 self.fn = fn
48 self.args = args
49 self.kwargs = kwargs
50
51 def run(self):
52 if not self.future.set_running_or_notify_cancel():
53 return
54
55 try:
56 result = self.fn(*self.args, **self.kwargs)
57 except BaseException as e:
58 self.future.set_exception(e)
59 else:
60 self.future.set_result(result)
61
62def _worker(executor_reference, work_queue):
63 try:
64 while True:
Antoine Pitrou27be5da2011-04-12 17:48:46 +020065 work_item = work_queue.get(block=True)
66 if work_item is not None:
67 work_item.run()
Andrew Svetlov6b973742012-11-03 15:36:01 +020068 # Delete references to object. See issue16284
69 del work_item
Antoine Pitrou27be5da2011-04-12 17:48:46 +020070 continue
Antoine Pitrouc13d4542011-03-26 19:29:44 +010071 executor = executor_reference()
72 # Exit if:
73 # - The interpreter is shutting down OR
74 # - The executor that owns the worker has been collected OR
75 # - The executor that owns the worker has been shutdown.
76 if _shutdown or executor is None or executor._shutdown:
77 # Notice other workers
78 work_queue.put(None)
79 return
80 del executor
Florent Xicluna04842a82011-11-11 20:05:50 +010081 except BaseException:
Brian Quinlan81c4d362010-09-18 22:35:02 +000082 _base.LOGGER.critical('Exception in worker', exc_info=True)
83
84class ThreadPoolExecutor(_base.Executor):
Gregory P. Smitha3d91b42017-06-21 23:41:13 -070085
86 # Used to assign unique thread names when thread_name_prefix is not supplied.
87 _counter = itertools.count().__next__
88
Gregory P. Smith50abe872016-08-07 10:19:20 -070089 def __init__(self, max_workers=None, thread_name_prefix=''):
Brian Quinlan81c4d362010-09-18 22:35:02 +000090 """Initializes a new ThreadPoolExecutor instance.
91
92 Args:
93 max_workers: The maximum number of threads that can be used to
94 execute the given calls.
Gregory P. Smith50abe872016-08-07 10:19:20 -070095 thread_name_prefix: An optional name prefix to give our threads.
Brian Quinlan81c4d362010-09-18 22:35:02 +000096 """
Guido van Rossumcfd46612014-09-02 10:39:18 -070097 if max_workers is None:
98 # Use this number because ThreadPoolExecutor is often
99 # used to overlap I/O instead of CPU work.
100 max_workers = (os.cpu_count() or 1) * 5
Brian Quinlan20efceb2014-05-17 13:51:10 -0700101 if max_workers <= 0:
102 raise ValueError("max_workers must be greater than 0")
103
Brian Quinlan81c4d362010-09-18 22:35:02 +0000104 self._max_workers = max_workers
105 self._work_queue = queue.Queue()
106 self._threads = set()
107 self._shutdown = False
108 self._shutdown_lock = threading.Lock()
Gregory P. Smitha3d91b42017-06-21 23:41:13 -0700109 self._thread_name_prefix = (thread_name_prefix or
110 ("ThreadPoolExecutor-%d" % self._counter()))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000111
112 def submit(self, fn, *args, **kwargs):
113 with self._shutdown_lock:
114 if self._shutdown:
115 raise RuntimeError('cannot schedule new futures after shutdown')
116
117 f = _base.Future()
118 w = _WorkItem(f, fn, args, kwargs)
119
120 self._work_queue.put(w)
121 self._adjust_thread_count()
122 return f
123 submit.__doc__ = _base.Executor.submit.__doc__
124
125 def _adjust_thread_count(self):
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100126 # When the executor gets lost, the weakref callback will wake up
127 # the worker threads.
128 def weakref_cb(_, q=self._work_queue):
129 q.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000130 # TODO(bquinlan): Should avoid creating new threads if there are more
131 # idle threads than items in the work queue.
Gregory P. Smith50abe872016-08-07 10:19:20 -0700132 num_threads = len(self._threads)
133 if num_threads < self._max_workers:
134 thread_name = '%s_%d' % (self._thread_name_prefix or self,
135 num_threads)
136 t = threading.Thread(name=thread_name, target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100137 args=(weakref.ref(self, weakref_cb),
138 self._work_queue))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000139 t.daemon = True
140 t.start()
141 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100142 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000143
144 def shutdown(self, wait=True):
145 with self._shutdown_lock:
146 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100147 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000148 if wait:
149 for t in self._threads:
150 t.join()
151 shutdown.__doc__ = _base.Executor.shutdown.__doc__