Last active
February 1, 2020 18:35
-
-
Save kunigami/c022b0586d41c662b8fc230d456867dc to your computer and use it in GitHub Desktop.
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
class Task(object): | |
def run(self): | |
while True: | |
try: | |
result = self.target.send(self.sendval) | |
if isinstance(result, SystemCall): | |
return result | |
# sub-routine call | |
if isinstance(result, types.GeneratorType): | |
# put the caller on the stack | |
self.stack.append(self.target) | |
self.sendval = None | |
self.target = result | |
else: | |
if not self.stack: | |
return | |
self.sendval = result | |
# resume execution to caller | |
self.target = self.stack.pop() | |
# current coroutine finished | |
except StopIteration: | |
# invalid state | |
if not self.stack: | |
raise | |
self.sendval = None | |
self.target = self.stack.pop() | |
# Example coroutine and sub-coroutine | |
def Accept(sock): | |
yield ReadWait(sock) | |
yield sock.accept() | |
def server(port): | |
# ... | |
while True: | |
# coroutine that calls another | |
client, addr = yield Accept(sock) | |
yield NewTask(handle_client(client, addr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment