blob: f9beb0f7f7ed3439b1dbf1c0dff861125e27e871 [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()
Andrew Svetlov6b973742012-11-03 15:36:01 +020066 # Delete references to object. See issue16284
67 del work_item
Antoine Pitrou27be5da2011-04-12 17:48:46 +020068 continue
Antoine Pitrouc13d4542011-03-26 19:29:44 +010069 executor = executor_reference()
70 # Exit if:
71 # - The interpreter is shutting down OR
72 # - The executor that owns the worker has been collected OR
73 # - The executor that owns the worker has been shutdown.
74 if _shutdown or executor is None or executor._shutdown:
75 # Notice other workers
76 work_queue.put(None)
77 return
78 del executor
Florent Xicluna04842a82011-11-11 20:05:50 +010079 except BaseException:
Brian Quinlan81c4d362010-09-18 22:35:02 +000080 _base.LOGGER.critical('Exception in worker', exc_info=True)
81
82class ThreadPoolExecutor(_base.Executor):
83 def __init__(self, max_workers):
84 """Initializes a new ThreadPoolExecutor instance.
85
86 Args:
87 max_workers: The maximum number of threads that can be used to
88 execute the given calls.
89 """
Brian Quinlan81c4d362010-09-18 22:35:02 +000090 self._max_workers = max_workers
91 self._work_queue = queue.Queue()
92 self._threads = set()
93 self._shutdown = False
94 self._shutdown_lock = threading.Lock()
95
96 def submit(self, fn, *args, **kwargs):
97 with self._shutdown_lock:
98 if self._shutdown:
99 raise RuntimeError('cannot schedule new futures after shutdown')
100
101 f = _base.Future()
102 w = _WorkItem(f, fn, args, kwargs)
103
104 self._work_queue.put(w)
105 self._adjust_thread_count()
106 return f
107 submit.__doc__ = _base.Executor.submit.__doc__
108
109 def _adjust_thread_count(self):
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100110 # When the executor gets lost, the weakref callback will wake up
111 # the worker threads.
112 def weakref_cb(_, q=self._work_queue):
113 q.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000114 # TODO(bquinlan): Should avoid creating new threads if there are more
115 # idle threads than items in the work queue.
116 if len(self._threads) < self._max_workers:
117 t = threading.Thread(target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100118 args=(weakref.ref(self, weakref_cb),
119 self._work_queue))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000120 t.daemon = True
121 t.start()
122 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100123 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000124
125 def shutdown(self, wait=True):
126 with self._shutdown_lock:
127 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100128 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000129 if wait:
130 for t in self._threads:
131 t.join()
132 shutdown.__doc__ = _base.Executor.shutdown.__doc__