Skip to content

Instantly share code, notes, and snippets.

@lemiant
Last active August 29, 2015 13:59
Show Gist options
  • Save lemiant/10660446 to your computer and use it in GitHub Desktop.
Save lemiant/10660446 to your computer and use it in GitHub Desktop.
Allows dead simple paralellization of a Python function call
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