blob: 93b495f55a3b4f0273859b88fb63f6c2235c3c3f [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
10import queue
11import threading
12import weakref
13
14# Workers are created as daemon threads. This is done to allow the interpreter
15# to exit when there are still idle threads in a ThreadPoolExecutor's thread
16# pool (i.e. shutdown() was not called). However, allowing workers to die with
17# the interpreter has two undesirable properties:
18# - The workers would still be running during interpretor shutdown,
19# meaning that they would fail in unpredictable ways.
20# - The workers could be killed while evaluating a work item, which could
21# be bad if the callable being evaluated has external side-effects e.g.
22# writing to a file.
23#
24# To work around this problem, an exit handler is installed which tells the
25# workers to exit when their work queues are empty and then waits until the
26# threads finish.
27
Antoine Pitrouc13d4542011-03-26 19:29:44 +010028_threads_queues = weakref.WeakKeyDictionary()
Brian Quinlan81c4d362010-09-18 22:35:02 +000029_shutdown = False
30
31def _python_exit():
32 global _shutdown
33 _shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +010034 items = list(_threads_queues.items())
35 for t, q in items:
36 q.put(None)
37 for t, q in items:
38 t.join()
Brian Quinlan81c4d362010-09-18 22:35:02 +000039
40atexit.register(_python_exit)
41
42class _WorkItem(object):
43 def __init__(self, future, fn, args, kwargs):
44 self.future = future
45 self.fn = fn
46 self.args = args
47 self.kwargs = kwargs
48
49 def run(self):
50 if not self.future.set_running_or_notify_cancel():
51 return
52
53 try:
54 result = self.fn(*self.args, **self.kwargs)
55 except BaseException as e:
56 self.future.set_exception(e)
57 else:
58 self.future.set_result(result)
59
60def _worker(executor_reference, work_queue):
61 try:
62 while True:
63 try:
Antoine Pitrouc13d4542011-03-26 19:29:44 +010064 work_item = work_queue.get(block=True)
Brian Quinlan81c4d362010-09-18 22:35:02 +000065 except queue.Empty:
Antoine Pitrouc13d4542011-03-26 19:29:44 +010066 pass
Brian Quinlan81c4d362010-09-18 22:35:02 +000067 else:
Antoine Pitrouc13d4542011-03-26 19:29:44 +010068 if work_item is not None:
69 work_item.run()
70 continue
71 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
Brian Quinlan81c4d362010-09-18 22:35:02 +000081 except BaseException as e:
82 _base.LOGGER.critical('Exception in worker', exc_info=True)
83
84class ThreadPoolExecutor(_base.Executor):
85 def __init__(self, max_workers):
86 """Initializes a new ThreadPoolExecutor instance.
87
88 Args:
89 max_workers: The maximum number of threads that can be used to
90 execute the given calls.
91 """
Brian Quinlan81c4d362010-09-18 22:35:02 +000092 self._max_workers = max_workers
93 self._work_queue = queue.Queue()
94 self._threads = set()
95 self._shutdown = False
96 self._shutdown_lock = threading.Lock()
97
98 def submit(self, fn, *args, **kwargs):
99 with self._shutdown_lock:
100 if self._shutdown:
101 raise RuntimeError('cannot schedule new futures after shutdown')
102
103 f = _base.Future()
104 w = _WorkItem(f, fn, args, kwargs)
105
106 self._work_queue.put(w)
107 self._adjust_thread_count()
108 return f
109 submit.__doc__ = _base.Executor.submit.__doc__
110
111 def _adjust_thread_count(self):
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100112 # When the executor gets lost, the weakref callback will wake up
113 # the worker threads.
114 def weakref_cb(_, q=self._work_queue):
115 q.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000116 # TODO(bquinlan): Should avoid creating new threads if there are more
117 # idle threads than items in the work queue.
118 if len(self._threads) < self._max_workers:
119 t = threading.Thread(target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100120 args=(weakref.ref(self, weakref_cb),
121 self._work_queue))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000122 t.daemon = True
123 t.start()
124 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100125 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000126
127 def shutdown(self, wait=True):
128 with self._shutdown_lock:
129 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100130 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000131 if wait:
132 for t in self._threads:
133 t.join()
134 shutdown.__doc__ = _base.Executor.shutdown.__doc__