1. 程式人生 > 其它 >python 協程二

python 協程二

技術標籤:python併發程式設計python併發程式設計

1 使用協程實現移動均值函式

>>> from inspect import getgeneratorstate as gs
>>> def mean_coroutine():
...   total = 0
...   count = 0
...   average = None
...   while True:
...     val = yield average
...     total += val
...     count += 1
...     average = total / count
... 
>>> avg_cor=mean_coroutine()
>>> gs(avg_cor)
'GEN_CREATED' 
>>> next(avg_cor)
>>> avg_cor.send(10)
10.0
>>> avg_cor.send(20)
15.0
>>> avg_cor.send(30)
20.0

2 使用裝飾器實現一個預激的協程

>>> def decorator(func):
...   def primer(*args,**kwarg):
...     cor = func(*args,**kwarg)
...     next(cor)
...     return cor
...   return primer
... 
>>> @decorator
... def mean_coroutine():
...   total = 0
...   count = 0
...   average = None
...   while True:
...     val = yield average
...     total += val
...     count += 1
...     average = total / count
... 
>>> from inspect import getgeneratorstate as gs
>>> avg_cor = mean_coroutine()
>>> gs(avg_cor)
'GEN_SUSPENDED'
>>> avg_cor.send(1)
1.0
>>> avg_cor.send(3)
2.0
>>> avg_cor.send(5)
3.0

https://blog.csdn.net/s695811494/article/details/112097536