Skip to content

Instantly share code, notes, and snippets.

@willkelly
Last active August 29, 2015 14:01
Show Gist options
  • Save willkelly/a2722dfb0aa435acacee to your computer and use it in GitHub Desktop.
Save willkelly/a2722dfb0aa435acacee to your computer and use it in GitHub Desktop.
Make threads that return values in python
import threading
class ThreadFunction(threading.Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
self._return = None
super(ThreadFunction, self).__init__(group, self._wrap(target),
name, args, kwargs, Verbose)
def _wrap(self, f):
def g(*args, **kwargs):
self._return = f(*args, **kwargs)
return g
def join(self):
super(ThreadFunction, self).join()
return self._return
@willkelly
Copy link
Author

>>> from thread_function import ThreadFunction
>>> def f(x):
...     return x
... 
>>> t1 = ThreadFunction(target=f, args=(1,))
>>> t1.start()
>>> t2 = ThreadFunction(target=f, args=(2,))
>>> t2.start()
>>> t1.join()
1
>>> t2.join()
2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment