【问题标题】:Tornado Execution Order Spawn callbackTornado 执行顺序 Spawn 回调
【发布时间】:2016-08-01 10:06:34
【问题描述】:

如果我有以下情况:

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

【问题讨论】:

    标签: tornado


    【解决方案1】:

    不,事实上,您可以保证所有函数都在它们开始运行之前生成,因为 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

    【讨论】:

    • 感谢您抽出宝贵的时间撰写杰西非常感谢。
    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2023-03-27
    • 2011-01-31
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多