Last active
October 5, 2015 09:48
-
-
Save mgedmin/2789186 to your computer and use it in GitHub Desktop.
value = runInThread(fn, args...) for Python
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 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