生成器到协程 - Go语言中文社区

生成器到协程


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()  #停止

协程预激

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/1ede1e43c613
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 13:08:39
  • 阅读 ( 1012 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

推荐文章

猜你喜欢