Skip to content

Instantly share code, notes, and snippets.

@matze
Created November 27, 2013 08:54
Show Gist options
  • Save matze/7672662 to your computer and use it in GitHub Desktop.
Save matze/7672662 to your computer and use it in GitHub Desktop.
@async based on gevent
import time
import gevent
import functools
class GreenletRunner(gevent.Greenlet):
def __init__(self, func, args, kwargs):
super(GreenletRunner, self).__init__()
self.func = func
self.args = args
self.kwargs = kwargs
def _run(self):
return self.func(*self.args, **self.kwargs)
def async(func):
@functools.wraps(func)
def _async(*args, **kwargs):
g = GreenletRunner(func, args, kwargs)
g.start()
return g
return _async
@async
def long_op(n=5):
try:
for i in range(n):
print(i)
gevent.sleep(1)
except gevent.GreenletExit:
print("Cleanup")
raise gevent.GreenletExit
return 'foo'
f = long_op()
print("Wait some time")
gevent.sleep(1.5)
f.kill()
print("Join that guy")
f.join()
print(f.get())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment