# 12.12 使用生成器代替线程¶

## 解决方案¶

```# Two simple generator functions
def countdown(n):
while n > 0:
print('T-minus', n)
yield
n -= 1
print('Blastoff!')

def countup(n):
x = 0
while x < n:
print('Counting up', x)
yield
x += 1
```

```from collections import deque

def __init__(self):

'''
Admit a newly started task to the scheduler
'''

def run(self):
'''
Run until there are no more tasks
'''
try:
# Run until the next yield statement
except StopIteration:
# Generator is no longer executing
pass

# Example use
sched.run()
```

`TaskScheduler` 类在一个循环中运行生成器集合——每个都运行到碰到yield语句为止。 运行这个例子，输出如下：

```T-minus 10
T-minus 5
Counting up 0
T-minus 9
T-minus 4
Counting up 1
T-minus 8
T-minus 3
Counting up 2
T-minus 7
T-minus 2
...
```

```from collections import deque

class ActorScheduler:
def __init__(self):
self._actors = {}          # Mapping of names to actors
self._msg_queue = deque()   # Message queue

def new_actor(self, name, actor):
'''
Admit a newly started actor to the scheduler and give it a name
'''
self._msg_queue.append((actor,None))
self._actors[name] = actor

def send(self, name, msg):
'''
Send a message to a named actor
'''
actor = self._actors.get(name)
if actor:
self._msg_queue.append((actor,msg))

def run(self):
'''
Run as long as there are pending messages.
'''
while self._msg_queue:
actor, msg = self._msg_queue.popleft()
try:
actor.send(msg)
except StopIteration:
pass

# Example use
if __name__ == '__main__':
def printer():
while True:
msg = yield
print('Got:', msg)

def counter(sched):
while True:
# Receive the current count
n = yield
if n == 0:
break
# Send to the printer task
sched.send('printer', n)
# Send the next count to the counter task (recursive)
sched.send('counter', n-1)

sched = ActorScheduler()
# Create the initial actors
sched.new_actor('printer', printer())
sched.new_actor('counter', counter(sched))

# Send an initial message to the counter to initiate
sched.send('counter', 10000)
sched.run()
```

```from collections import deque
from select import select

# This class represents a generic yield event in the scheduler
class YieldEvent:
def handle_yield(self, sched, task):
pass

def handle_resume(self, sched, task):
pass

class Scheduler:
def __init__(self):
self._numtasks = 0       # Total num of tasks
self._write_waiting = {} # Tasks waiting to write

# Poll for I/O events and restart waiting tasks
def _iopoll(self):
self._write_waiting,[])
for r in rset:
for w in wset:
evt, task = self._write_waiting.pop(w)

'''
Add a newly started task to the scheduler
'''

'''
msg is what to send into the task when it resumes.
'''

# Add a task to the write set
def _write_wait(self, fileno, evt, task):
self._write_waiting[fileno] = (evt, task)

def run(self):
'''
Run the task scheduler until there are no tasks
'''
self._iopoll()
try:
# Run the coroutine to the next yield
if isinstance(r, YieldEvent):
else:
raise RuntimeError('unrecognized yield event')
except StopIteration:

# Example implementation of coroutine-based socket I/O
def __init__(self, sock, nbytes):
self.sock = sock
self.nbytes = nbytes
def handle_yield(self, sched, task):
def handle_resume(self, sched, task):
data = self.sock.recv(self.nbytes)

class WriteSocket(YieldEvent):
def __init__(self, sock, data):
self.sock = sock
self.data = data

def handle_yield(self, sched, task):

def handle_resume(self, sched, task):
nsent = self.sock.send(self.data)

class AcceptSocket(YieldEvent):
def __init__(self, sock):
self.sock = sock

def handle_yield(self, sched, task):

def handle_resume(self, sched, task):
r = self.sock.accept()

# Wrapper around a socket object for use with yield
class Socket(object):
def __init__(self, sock):
self._sock = sock

def recv(self, maxbytes):

def send(self, data):
return WriteSocket(self._sock, data)

def accept(self):
return AcceptSocket(self._sock)

def __getattr__(self, name):
return getattr(self._sock, name)

if __name__ == '__main__':
from socket import socket, AF_INET, SOCK_STREAM
import time

# Example of a function involving generators.  This should
# be called using line = yield from readline(sock)
chars = []
while True:
c = yield sock.recv(1)
if not c:
break
chars.append(c)
if c == b'\n':
break
return b''.join(chars)

# Echo server using generators
class EchoServer:
self.sched = sched

s = Socket(socket(AF_INET,SOCK_STREAM))

s.listen(5)
while True:
c,a = yield s.accept()
print('Got connection from ', a)
self.sched.new(self.client_handler(Socket(c)))

def client_handler(self,client):
while True:
line = yield from readline(client)
if not line:
break
line = b'GOT:' + line
while line:
nsent = yield client.send(line)
line = line[nsent:]
client.close()
print('Client closed')

sched = Scheduler()
EchoServer(('',16000),sched)
sched.run()
```

## 讨论¶

```def some_generator():
...
result = yield data
...
```

```f = some_generator()

# Initial result. Is None to start since nothing has been computed
result = None
while True:
try:
data = f.send(result)
result = ... do some calculation ...
except StopIteration:
break
```

PEP 3156 同样有一个关于使用协程的异步I/O模型。 特别的，你不可能自己去实现一个底层的协程调度器。 不过，关于协程的思想是很多流行库的基础， 包括 gevent, greenlet, Stackless Python 以及其他类似工程。