不,事实上,您可以保证所有函数都在它们开始运行之前生成,因为 first 在生成 func 和生成 func2 之间不会出现 yield。您可以通过测试您的代码自己验证这一点:
from tornado import gen, ioloop
@gen.coroutine
def func():
print('func started')
yield gen.moment
print('func done')
@gen.coroutine
def func2():
print('func2 started')
yield gen.moment
print('func2 done')
@gen.coroutine
def first():
for i in range(2):
ioloop.IOLoop.current().spawn_callback(func)
ioloop.IOLoop.current().spawn_callback(func2)
yield gen.sleep(1)
ioloop.IOLoop.current().run_sync(first)
打印出来:
func started
func started
func2 started
func done
func done
func2 done
看,func2 在运行 func 的协程完成之前开始。
完成你想要的:
@gen.coroutine
def first():
yield [func() for i in range(2)]
ioloop.IOLoop.current().spawn_callback(func2)
打印出来:
func started
func started
func done
func done
func2 started
func2 done
如果您希望first 在退出之前等待func2 完成,那么:
@gen.coroutine
def first():
yield [func() for i in range(2)]
yield func2()
有关从协程调用协程的更多信息,请参阅我的Refactoring Tornado Coroutines。