Created
March 8, 2015 19:10
-
-
Save perillo/21234cf7b06873227cb2 to your computer and use it in GitHub Desktop.
Synchronous call an asynchronous, callback based, function
This file contains 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
#!/usr/bin/env python3 | |
import threading | |
import time | |
def syncc(f, *args, **kwargs): | |
"""syncc calls the asynchronous function f with supplied | |
parameters, waiting until the function callback is called, and returning | |
the received parameters. | |
""" | |
def callback(*cargs, **ckwargs): | |
r.append((cargs, ckwargs)) | |
with cv: | |
cv.notify() | |
r = [] | |
cv = threading.Condition() | |
with cv: | |
f(*args, callback=callback, **kwargs) | |
cv.wait() | |
return r[0][0], r[0][1] | |
if __name__ == "__main__": | |
def test(a, b, callback): | |
print("test called with parameters {}, {} and callback {}".format(a, b, callback)) | |
def task(): | |
print("task called in a separate thread") | |
time.sleep(5) | |
print("task done, calling callback") | |
callback(a + b) | |
th = threading.Thread(target=task) | |
th.start() | |
r = syncc(test, 1, 2) | |
print(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment