Last active
August 29, 2015 13:59
-
-
Save lemiant/10660446 to your computer and use it in GitHub Desktop.
Allows dead simple paralellization of a Python function call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def async(func): | |
"""A decorator to make a function run in its own thread and return its result on .join()""" | |
def launch(*args, **kwargs): | |
target = ThreadedFunction(func, *args, **kwargs) | |
target.start() | |
return target | |
return launch | |
class ThreadedFunction(threading.Thread): | |
def __init__(self, func, *args, **kwargs): | |
self.args = args | |
self.kwargs = kwargs | |
self.func = func | |
threading.Thread.__init__(self) | |
def run(self): | |
self.result = self.func(*self.args, **self.kwargs) | |
def join(self): | |
threading.Thread.join(self) | |
return self.result | |
# ===================================== | |
#Example usage: | |
@async | |
async_load(path): | |
with open(path) as f: | |
return f.read() | |
pointer = async_load("hello_world.txt") | |
# Other computations... | |
print pointer.join() | |
# >Hello World |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment