Created
December 1, 2011 07:21
-
-
Save yyuu/1414604 to your computer and use it in GitHub Desktop.
a coroutine implementation that can work with tornado.ioloop
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 python | |
import tornado.ioloop | |
class Coroutine(object): | |
""" | |
a coroutine implementation that can work with tornado.ioloop | |
def generator(): | |
print('A') | |
yield | |
print('B') | |
def finished(): | |
print('Z') | |
co = Coroutine(generator) | |
co(finished) | |
-- | |
A | |
B | |
Z | |
""" | |
def __init__(self, generator, io_loop=None): | |
self.generator = generator | |
self.iterator = None | |
self.io_loop = tornado.ioloop.IOLoop.instance() if io_loop is None else io_loop | |
self.alive = True | |
def __call__(self, *args): | |
try: | |
if self.iterator is None: | |
self.iterator = self.generator(*args) | |
response = next(self.iterator) | |
else: | |
if 0 < len(args): | |
response = self.iterator.send(*args) | |
else: | |
response = next(self.iterator) | |
self.io_loop.add_callback(self) | |
except StopIteration: | |
self.alive = False | |
# vim:set ft=python : |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment