|
| 1 | +# Copyright 2009-2015 Ram Rachum. |
| 2 | +# This program is distributed under the MIT license. |
| 3 | + |
| 4 | +import time |
| 5 | +import concurrent.futures |
| 6 | + |
| 7 | +from python_toolbox import sequence_tools |
| 8 | + |
| 9 | + |
| 10 | +class CuteExecutorMixin: |
| 11 | + def filter(self, filter_function, iterable, timeout=None, |
| 12 | + as_completed=False): |
| 13 | + '''Get a parallelized version of filter(filter_function, iterable).''' |
| 14 | + |
| 15 | + sequence = sequence_tools.ensure_iterable_is_sequence(iterable) |
| 16 | + return ( |
| 17 | + item for (item, keep) in zip( |
| 18 | + sequence, |
| 19 | + self.map(filter_function, sequence, timeout=timeout, |
| 20 | + as_completed=as_completed) |
| 21 | + ) if keep |
| 22 | + ) |
| 23 | + |
| 24 | + def map(self, function, *iterables, timeout=None, as_completed=False): |
| 25 | + '''Get a parallelized version of map(function, iterable).''' |
| 26 | + |
| 27 | + if timeout is not None: |
| 28 | + end_time = timeout + time.time() |
| 29 | + |
| 30 | + futures = [self.submit(function, *args) for args in zip(*iterables)] |
| 31 | + futures_iterator = concurrent.futures.as_completed(futures) if \ |
| 32 | + as_completed else futures |
| 33 | + |
| 34 | + # Yield must be hidden in closure so that the futures are submitted |
| 35 | + # before the first iterator value is required. |
| 36 | + def result_iterator(): |
| 37 | + try: |
| 38 | + for future in futures: |
| 39 | + if timeout is None: |
| 40 | + yield future.result() |
| 41 | + else: |
| 42 | + yield future.result(end_time - time.time()) |
| 43 | + finally: |
| 44 | + for future in futures: |
| 45 | + future.cancel() |
| 46 | + return result_iterator() |
| 47 | + |
| 48 | + |
| 49 | +class CuteThreadPoolExecutor(CuteExecutorMixin, |
| 50 | + concurrent.futures.ThreadPoolExecutor): |
| 51 | + pass |
| 52 | + |
| 53 | +class CuteProcessPoolExecutor(CuteExecutorMixin, |
| 54 | + concurrent.futures.ProcessPoolExecutor): |
| 55 | + pass |
0 commit comments