blob: fbac0887a591b9fcaca15c89dde632cd0b96f533 [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:
Antoine Pitrou27be5da2011-04-12 17:48:46 +020063 work_item = work_queue.get(block=True)
64 if work_item is not None:
65 work_item.run()
66 continue
Antoine Pitrouc13d4542011-03-26 19:29:44 +010067 executor = executor_reference()
68 # Exit if:
69 # - The interpreter is shutting down OR
70 # - The executor that owns the worker has been collected OR
71 # - The executor that owns the worker has been shutdown.
72 if _shutdown or executor is None or executor._shutdown:
73 # Notice other workers
74 work_queue.put(None)
75 return
76 del executor
Brian Quinlan81c4d362010-09-18 22:35:02 +000077 except BaseException as e:
78 _base.LOGGER.critical('Exception in worker', exc_info=True)
79
80class ThreadPoolExecutor(_base.Executor):
81 def __init__(self, max_workers):
82 """Initializes a new ThreadPoolExecutor instance.
83
84 Args:
85 max_workers: The maximum number of threads that can be used to
86 execute the given calls.
87 """
Brian Quinlan81c4d362010-09-18 22:35:02 +000088 self._max_workers = max_workers
89 self._work_queue = queue.Queue()
90 self._threads = set()
91 self._shutdown = False
92 self._shutdown_lock = threading.Lock()
93
94 def submit(self, fn, *args, **kwargs):
95 with self._shutdown_lock:
96 if self._shutdown:
97 raise RuntimeError('cannot schedule new futures after shutdown')
98
99 f = _base.Future()
100 w = _WorkItem(f, fn, args, kwargs)
101
102 self._work_queue.put(w)
103 self._adjust_thread_count()
104 return f
105 submit.__doc__ = _base.Executor.submit.__doc__
106
107 def _adjust_thread_count(self):
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100108 # When the executor gets lost, the weakref callback will wake up
109 # the worker threads.
110 def weakref_cb(_, q=self._work_queue):
111 q.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000112 # TODO(bquinlan): Should avoid creating new threads if there are more
113 # idle threads than items in the work queue.
114 if len(self._threads) < self._max_workers:
115 t = threading.Thread(target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100116 args=(weakref.ref(self, weakref_cb),
117 self._work_queue))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000118 t.daemon = True
119 t.start()
120 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100121 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000122
123 def shutdown(self, wait=True):
124 with self._shutdown_lock:
125 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100126 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000127 if wait:
128 for t in self._threads:
129 t.join()
130 shutdown.__doc__ = _base.Executor.shutdown.__doc__