python coroutine的运行过程

Python (179) 2023-07-13 07:36:24

说明

1、先调用函数获取生成器对象,再调用next方法或send(None)方法打开coroutine。

2、函数执行到yield位置,返回yield后挂起,把控制流交回主线程。再调用send法时,可以传输数据并激活协程。

继续执行到最后或下一个yield语句。

实例

"""
#BEGINCORO_AVERAGER_TEST
>>>coro_avg=averager()#<1>
>>>next(coro_avg)#<2>
>>>coro_avg.send(10)#<3>
10.0
>>>coro_avg.send(30)
20.0
>>>coro_avg.send(5)
15.0
#ENDCORO_AVERAGER_TEST
"""
defaverager():
total=0.0
count=0
average=None
whileTrue:#<1>
term=yieldaverage#<2>
total+=term
count+=1
average=total/count

以上就是python coroutine的运行过程,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复