第一次调用send,代码返回value(5)之后在第5行挂起, 然后generator throw之后会被第6行catch住。如不雅第7行没有从新yield,那么会从新抛出StopIteration异常。
留意事项
如不雅一个生成器已经经由过程send开端履行,那么在其再次yield之前,是不克不及大年夜其他生成器再次调剂到该生成器
- @consumer
- def funcA():
- while True:
- data = yield
- print 'funcA recevie', data
- fb.send(data * 2)
- @consumer
- def funcB():
- while True:
- data = yield
- print 'funcB recevie', data
- fa.send(data * 2)
- fa = funcA()
- fb = funcB()
- if __name__ == '__main__':
- fa.send(10)
输出:
- funcA recevie 10
- funcB recevie 20
- ValueError: generator already executing
Generator 与 Coroutine
Python中,generator的send和throw办法使得generator很像一个协程(coroutine), 然则generator只是一个半协程(semicoroutines),python doc是如许描述的:
“All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than>
推荐阅读
本文的目标是以“输入 URL 后产生了什么”这个经典面试题为引子,写一篇既可以或许涵盖面试中大年夜部分收集试题,又可以或许将“输入 URL 后产生什么”讲得有深度的>>>详细阅读
本文标题:Python增强的生成器:协程
地址:http://www.17bianji.com/lsqh/37169.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示