Tornado:线程在协同程序中没有开始使用@run_on \u executor

2024-09-30 14:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这次龙卷风测试中遇到了以下问题:

class SimpleIOLoopTests(tornado.testing.AsyncTestCase):
    def setUp(self):
        super(SimpleIOLoopTests, self).setUp()

    def test_executor_future(self):
        self.executor = ThreadPoolExecutor(2)

        @run_on_executor
        def wait_and_return_a_value():
            time.sleep(2)
            return 20

        @coroutine
        def async_compare(callback):
            val = yield wait_and_return_a_value()
            assert_that(val, equal_to(20))

            callback()

        async_compare(self.stop)
        self.wait()

关键是测试只是循环,直到超时。调试代码看起来好像executor future是作为done()创建的,因此,甚至没有由io峎u循环启动。在

我做错什么了?我们非常感谢您的帮助

顺便说一句:如果我使用@return_future decorator创建了一个琐碎的future,也会发生同样的情况(对于这一点,已经做了一个意外的事实)

^{pr2}$

谢谢和问候 马库斯


Tags: andselfasyncreturnvaluedefsetupcallback
1条回答
网友
1楼 · 发布于 2024-09-30 14:28:44

问题是执行器必须“活”在一个定义了io\u循环和executor的类中(这可以在检查@run_on_executor decorator时看到)。在

def test_executor_future(self):
    class Executor():
        def __init__(self, io_loop=None):
            self.io_loop = io_loop or IOLoop.instance()
            self.executor = ThreadPoolExecutor(2)

        @tornado.concurrent.run_on_executor
        def wait_and_return_a_value(self):
            return 20

        def destroy(self):
            self.executor.shutdown(1)

    @tornado.gen.coroutine
    def async_compare(callback):
        executor = Executor()
        val = yield executor.wait_and_return_a_value()
        assert_that(val, equal_to(20))

        executor.destroy()
        callback()

    async_compare(self.stop)
    self.wait()

相关问题 更多 >