Make parallelize remember to shutdown the default executors atexit.
[python_utils.git] / parallelize.py
1 #!/usr/bin/env python3
2
3 """A decorator to help with dead simple parallelization."""
4
5 import atexit
6 from enum import Enum
7 import functools
8 import typing
9
10
11 class Method(Enum):
12     THREAD = 1
13     PROCESS = 2
14     REMOTE = 3
15
16
17 def parallelize(
18     _funct: typing.Optional[typing.Callable] = None, *, method: Method = Method.THREAD
19 ) -> typing.Callable:
20     """Usage:
21
22         @parallelize    # defaults to thread-mode
23         def my_function(a, b, c) -> int:
24             ...do some slow / expensive work, e.g., an http request
25
26         @parallelize(method=Method.PROCESS)
27         def my_other_function(d, e, f) -> str:
28             ...do more really expensice work, e.g., a network read
29
30         @parallelize(method=Method.REMOTE)
31         def my_other_other_function(g, h) -> int:
32             ...this work will be distributed to a remote machine pool
33
34     This decorator will invoke the wrapped function on:
35
36         Method.THREAD (default): a background thread
37         Method.PROCESS: a background process
38         Method.REMOTE: a process on a remote host
39
40     The wrapped function returns immediately with a value that is
41     wrapped in a SmartFuture.  This value will block if it is either
42     read directly (via a call to result._resolve) or indirectly (by
43     using the result in an expression, printing it, hashing it,
44     passing it a function argument, etc...).  See comments on the
45     SmartFuture class for details.
46
47     Note: you may stack @parallelized methods and it will "work".
48     That said, having multiple layers of Method.PROCESS or
49     Method.REMOTE may prove to be problematic because each process in
50     the stack will use its own independent pool which may overload
51     your machine with processes or your network with remote processes
52     beyond the control mechanisms built into one instance of the pool.
53     Be careful.
54
55     Also note: there is a non trivial overhead of pickling code and
56     scp'ing it over the network when you use Method.REMOTE.  There's
57     a smaller but still considerable cost of creating a new process
58     and passing code to/from it when you use Method.PROCESS.
59     """
60
61     def wrapper(funct: typing.Callable):
62         @functools.wraps(funct)
63         def inner_wrapper(*args, **kwargs):
64             import executors
65             import smart_future
66
67             # Look for as of yet unresolved arguments in _funct's
68             # argument list and resolve them now.
69             newargs = []
70             for arg in args:
71                 newargs.append(smart_future.SmartFuture.resolve(arg))
72             newkwargs = {}
73             for kw in kwargs:
74                 newkwargs[kw] = smart_future.SmartFuture.resolve(kwargs[kw])
75
76             executor = None
77             if method == Method.PROCESS:
78                 executor = executors.DefaultExecutors().process_pool()
79             elif method == Method.THREAD:
80                 executor = executors.DefaultExecutors().thread_pool()
81             elif method == Method.REMOTE:
82                 executor = executors.DefaultExecutors().remote_pool()
83             assert executor is not None
84             atexit.register(executors.DefaultExecutors().shutdown)
85
86             future = executor.submit(funct, *newargs, **newkwargs)
87
88             # Wrap the future that's returned in a SmartFuture object
89             # so that callers do not need to call .result(), they can
90             # just use is as normal.
91             return smart_future.SmartFuture(future)
92
93         return inner_wrapper
94
95     if _funct is None:
96         return wrapper
97     else:
98         return wrapper(_funct)