2016-08-01 30 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

感謝您抽出時間寫出傑西非常感謝。 –