Skip to content

Instantly share code, notes, and snippets.

@perillo
Created March 8, 2015 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perillo/21234cf7b06873227cb2 to your computer and use it in GitHub Desktop.
Save perillo/21234cf7b06873227cb2 to your computer and use it in GitHub Desktop.
Synchronous call an asynchronous, callback based, function
#!/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