我可以连接两个协程 A 和 B,A 会激发 B,B 会激发 A?例如,A 将接受一个数字,打印它并使用 (number+1) 调用 B。B 将打印它并使用 (number+1) 调用 A。我希望 1,2,3,4,5,... 打印
不幸的是,这段代码确实按预期工作
def coroutine(func):
def start(*args,**kwargs):
cr = func(*args,**kwargs)
cr.next()
return cr
return start
_target_from_a = None
_target_from_b = None
@coroutine
def func_a():
while True:
item = yield
print 'a', item
_target_from_a.send(item + 1)
@coroutine
def func_b():
while True:
item = yield
print 'b', item
_target_from_b.send(item + 1)
a = func_a()
b = func_b()
_target_from_a = b
_target_from_b = a
a.send(1)
它产生以下错误:
a 1
b 2
Traceback (most recent call last):
File "coloop.py", line 31, in <module>
a.send(1)
File "coloop.py", line 17, in func_a
_target_from_a.send(item + 1)
File "coloop.py", line 24, in func_b
_target_from_b.send(item + 1)
ValueError: generator already executing