Skip to content

Instantly share code, notes, and snippets.

@kunigami
Last active February 1, 2020 18:35
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 kunigami/c022b0586d41c662b8fc230d456867dc to your computer and use it in GitHub Desktop.
Save kunigami/c022b0586d41c662b8fc230d456867dc to your computer and use it in GitHub Desktop.
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