生成器到协程
2019-03-06 本文已影响0人
低吟浅唱1990
def simple_coroutine():
print('->coroutine started')
x = yield
print('-> coroutine received:',x*2)
>>>my_coro = simple_coroutine()
>>>my_coro
>>><generator object simple_coroutine at 0x000000000068A2B0>
>>>next(my_coro)
->coroutine started
>>>my_coro.send(42)
-> coroutine received: 84
程序会在yield处挂起,产出None值 因为yield关键字右边没有表达式
from inspect import getgeneratorstate #执行过程中的状态显示
def simple_coro2(a):
print('-> Started:a=',a)
b = yield a
print('-> Received: b = ',b)
c = yield a + b
print('-> Received: c = ',c)
my_coro2 = simple_coro2(14)
getgeneratorstate(my_coro2)
next(my_coro2)
getgeneratorstate(my_coro2)
my_coro2.send(28)
my_coro2.send(99)
-> Started:a= 14
-> Received: b = 28
-> Received: c = 99
协程在yield关键字所在的位置暂停执行。在赋值语句中, = 右边的代码在赋值之前执行。因此,对于 b = yield a 这行代码来说。等到客户端再激活协程时才会设定b的值。
image.png
def averager():
total = 0.0
count = 0
averager = None
while True:
term = yield averager #yield 表达式用于暂停执行协程, 把结果发给调用方; 还用于接收调用方后面发给协程的值, 恢复无限循环。
total += term
count += 1
averager = total/count
>>>coro_avg = averager() #创建协程
>>>next(coro_avg) # 调用next 预激协程
>>>print(coro_avg.send(18)) # 计算平均值
>>>18
>>>print(coro_avg.send(30))
>>>24
>>>coro_avg.close() #停止