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