Skip to content

Instantly share code, notes, and snippets.

@mgedmin
Last active October 5, 2015 09:48
Show Gist options
  • Save mgedmin/2789186 to your computer and use it in GitHub Desktop.
Save mgedmin/2789186 to your computer and use it in GitHub Desktop.
value = runInThread(fn, args...) for Python
def runInThread(fn, *args, **kw):
"""Execute fn(*args, **kw) in a new thread context and return the result.
The execution is synchronous, i.e. blocking.
Typical use cases for runInThread will be the inspection of side effects
that are normally invisible to other threads until you commit a transaction
or something like that.
"""
# Aargh! Why can't threading.Thread(target=fn).join() return the result of
# fn()? This whole function should be a one-liner, dammit!
result = []
error = []
def wrapper():
try:
result.append(fn(*args, **kw))
except:
error.extend(sys.exc_info())
t = threading.Thread(target=wrapper)
t.start()
t.join()
if error:
raise error[0], error[1], error[2]
return result[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment