Tornado 执行命令 Spawn 回调

Tornado Execution Order Spawn callback

如果我有类似以下内容:

 @tornado.gen.coroutine
 def first(x):
    # 
    # do stuff


    for i in I:
       tornado.ioloop.IOLoop.current().spawn_callback(func,i)

    tornado.ioloop.IOLoop.current().spawn_callback(func2,z)

 yield first(xxx)

我能否保证 for 循环中的所有派生函数都将 运行 在最后一次派生回调到 func2() 之前?

不,事实上,您可以保证所有函数都在任何函数启动之前生成 运行,因为 first 在生成 func 之间不会 yield并产卵 func2。您可以通过测试您的代码自己验证这一点:

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