Skip to main content
 首页 » 编程设计

python之协程尾旋

2024年11月01日8artech

我能否连接两个协程 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) 

它产生以下 error :

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 

请您参考如下方法:

当你做 _target_from_a.send(something) a协程,在被yield“暂停”之前 调用 b它恢复执行,它所做的是:

    item = yield 
    print 'b', item 
    _target_from_b.send(item + 1)   # ARGH!! 

问题是 _target_from_b.send(item + 1)将尝试调用 a .但是a in this instant 没有等待任何东西,它仍在执行。

请记住,协程在执行时就像任何其他函数一样。打电话_target_from_a.send() 不会暂停协程,但 python 只是执行函数调用。

总结:永远不要使用协程进行循环。他们根本无法工作。

请注意 generator already executing从多个线程访问同一个生成器/协程时也可能引发异常。


我建议您阅读 "A Curious Course on Coroutines and Concurrency"作者 David Beazley,他很好地解释了协程的使用方法和工作原理。