Python 协程的无限递归的问题,python协程递归,hi, 最近看了关于Py


hi, 最近看了关于Python协程的相关文章协程的简单理解,说协程可以无限递归,于是想写一个协程示例练练,于是:

import timedef ping():    print 'ping 0'    count = 1    try:        pi,po = yield s        print 'ping ' + str(count)        count += 1             time.sleep(1)        po.send([po, pi])    except StopIteration:        passdef pong():    print 'pong 0'    count = 1    try:        po, pi = yield s        print 'pong ' + str(count)        count += 1        time.sleep(1)        pi.send([pi,po])    except StopIteration:        passs = ping()r = pong()s.next()r.next()s.send([s,r])

运行结果是:

ping 0pong 0ping 1pong 1Traceback (most recent call last):  File "D:\test\coroutine.py", line 34, in <module>    s.send([s,r])  File "D:\test\coroutine.py", line 12, in ping    po.send([po, pi])  File "D:\test\coroutine.py", line 25, in pong    pi.send([pi,po])ValueError: generator already executing

那篇文章使用了stackless,我想实现一个原始的方法。但是出错,不知道要实现无限递归的话,应该怎么写嘞?

编橙之家文章,

评论关闭