2016-08-01 34 views
1

如果我有类似如下:龙卷风执行顺序菌种回调

@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之前运行()?

回答

5

不,其实你保证,所有的功能都催生了其中任何一个开始运行之前,因为firstyield产卵func和产卵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

+0

感谢您抽出时间写出杰西非常感谢。 –