Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 1 | # 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 | |
| 8 | import atexit |
| 9 | from concurrent.futures import _base |
| 10 | import queue |
| 11 | import threading |
| 12 | import 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 Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 28 | _threads_queues = weakref.WeakKeyDictionary() |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 29 | _shutdown = False |
| 30 | |
| 31 | def _python_exit(): |
| 32 | global _shutdown |
| 33 | _shutdown = True |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 34 | 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 Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 39 | |
| 40 | atexit.register(_python_exit) |
| 41 | |
| 42 | class _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 | |
| 60 | def _worker(executor_reference, work_queue): |
| 61 | try: |
| 62 | while True: |
Antoine Pitrou | 27be5da | 2011-04-12 17:48:46 +0200 | [diff] [blame] | 63 | work_item = work_queue.get(block=True) |
| 64 | if work_item is not None: |
| 65 | work_item.run() |
| 66 | continue |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 67 | 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 Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 77 | except BaseException as e: |
| 78 | _base.LOGGER.critical('Exception in worker', exc_info=True) |
| 79 | |
| 80 | class 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 Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 88 | 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 Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 108 | # 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 Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 112 | # 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 Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 116 | args=(weakref.ref(self, weakref_cb), |
| 117 | self._work_queue)) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 118 | t.daemon = True |
| 119 | t.start() |
| 120 | self._threads.add(t) |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 121 | _threads_queues[t] = self._work_queue |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 122 | |
| 123 | def shutdown(self, wait=True): |
| 124 | with self._shutdown_lock: |
| 125 | self._shutdown = True |
Antoine Pitrou | c13d454 | 2011-03-26 19:29:44 +0100 | [diff] [blame] | 126 | self._work_queue.put(None) |
Brian Quinlan | 81c4d36 | 2010-09-18 22:35:02 +0000 | [diff] [blame] | 127 | if wait: |
| 128 | for t in self._threads: |
| 129 | t.join() |
| 130 | shutdown.__doc__ = _base.Executor.shutdown.__doc__ |