summaryrefslogtreecommitdiff
path: root/trollius/executor.py
blob: 9e7fdd780b8840af986cb35e8c1df7a30c8c3e62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from .log import logger

__all__ = (
    'CancelledError', 'TimeoutError',
    'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
    )

# Argument for default thread pool executor creation.
_MAX_WORKERS = 5

try:
    import concurrent.futures
    import concurrent.futures._base
except ImportError:
    FIRST_COMPLETED = 'FIRST_COMPLETED'
    FIRST_EXCEPTION = 'FIRST_EXCEPTION'
    ALL_COMPLETED = 'ALL_COMPLETED'

    class Future(object):
        def __init__(self, callback, args):
            try:
                self._result = callback(*args)
                self._exception = None
            except Exception as err:
                self._result = None
                self._exception = err
            self.callbacks = []

        def cancelled(self):
            return False

        def done(self):
            return True

        def exception(self):
            return self._exception

        def result(self):
            if self._exception is not None:
                raise self._exception
            else:
                return self._result

        def add_done_callback(self, callback):
            callback(self)

    class Error(Exception):
        """Base class for all future-related exceptions."""
        pass

    class CancelledError(Error):
        """The Future was cancelled."""
        pass

    class TimeoutError(Error):
        """The operation exceeded the given deadline."""
        pass

    class SynchronousExecutor:
        """
        Synchronous executor: submit() blocks until it gets the result.
        """
        def submit(self, callback, *args):
            return Future(callback, args)

        def shutdown(self, wait):
            pass

    def get_default_executor():
        logger.error("concurrent.futures module is missing: "
                     "use a synchrounous executor as fallback!")
        return SynchronousExecutor()
else:
    FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
    FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
    ALL_COMPLETED = concurrent.futures.ALL_COMPLETED

    Future = concurrent.futures.Future
    Error = concurrent.futures._base.Error
    CancelledError = concurrent.futures.CancelledError
    TimeoutError = concurrent.futures.TimeoutError

    def get_default_executor():
        return concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)