blob: 8d6081cf15a56b9ad05d3ae97ef3c1e4f9afd1ba [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 Quinlan20efceb2014-05-17 13:51:10 -070090 if max_workers <= 0:
91 raise ValueError("max_workers must be greater than 0")
92
Brian Quinlan81c4d362010-09-18 22:35:02 +000093 self._max_workers = max_workers
94 self._work_queue = queue.Queue()
95 self._threads = set()
96 self._shutdown = False
97 self._shutdown_lock = threading.Lock()
98
99 def submit(self, fn, *args, **kwargs):
100 with self._shutdown_lock:
101 if self._shutdown:
102 raise RuntimeError('cannot schedule new futures after shutdown')
103
104 f = _base.Future()
105 w = _WorkItem(f, fn, args, kwargs)
106
107 self._work_queue.put(w)
108 self._adjust_thread_count()
109 return f
110 submit.__doc__ = _base.Executor.submit.__doc__
111
112 def _adjust_thread_count(self):
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100113 # When the executor gets lost, the weakref callback will wake up
114 # the worker threads.
115 def weakref_cb(_, q=self._work_queue):
116 q.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000117 # TODO(bquinlan): Should avoid creating new threads if there are more
118 # idle threads than items in the work queue.
119 if len(self._threads) < self._max_workers:
120 t = threading.Thread(target=_worker,
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100121 args=(weakref.ref(self, weakref_cb),
122 self._work_queue))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000123 t.daemon = True
124 t.start()
125 self._threads.add(t)
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100126 _threads_queues[t] = self._work_queue
Brian Quinlan81c4d362010-09-18 22:35:02 +0000127
128 def shutdown(self, wait=True):
129 with self._shutdown_lock:
130 self._shutdown = True
Antoine Pitrouc13d4542011-03-26 19:29:44 +0100131 self._work_queue.put(None)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000132 if wait:
133 for t in self._threads:
134 t.join()
135 shutdown.__doc__ = _base.Executor.shutdown.__doc__