Created
November 27, 2013 08:54
-
-
Save matze/7672662 to your computer and use it in GitHub Desktop.
@async based on gevent
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
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