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