python - Tornado :线程未在协程中使用 @run_on_executor 启动

标签 python tornado coroutine

我在这个小 Tornado 测试中遇到以下问题:

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()

重点是测试只是循环,直到发生超时。调试代码,它看起来好像执行程序 future 是作为 did() 创建的,因此甚至没有由 io_loop 启动。

我在这里做错了什么?非常感谢您对这个问题的帮助

顺便说一句:如果我使用像这样的 @return_future 装饰器创建一个简单的 future,也会发生同样的情况(对于它来说,意外的是已经完成了)

@return_future
    def get_value(callback):
        callback(10)

感谢和问候 马库斯

最佳答案

问题是执行器必须“存在”在定义了 io_loop 和执行器的类中(当您检查 @run_on_executor 装饰器时可以看到这一点)。

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()

关于python - Tornado :线程未在协程中使用 @run_on_executor 启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860829/

相关文章:

python - 什么会导致 asyncio.new_event_loop() 的简单调用挂起?

python - 奇怪的 MySQL Python mod_wsgi Can't connect to MySQL server on 'localhost' (49) 问题

python - 在 Tornado 中使用 Django ORM, "syncdb"不起作用

python - 在 Tornado 中保留 websocket 连接列表

python - 在 Tornado 中全局访问 Web 请求

python - 如何用一个线程监听redis的所有订阅 channel ?

python - python中每小时的平均数据

python - 为什么我的示例 google api 代码(python、admin、directory_v1)上出现 503 服务不可用?

python - Python 中的空返回是什么意思?

python - 在 python 中,有没有办法在调用函数之前检查函数是否为 "generator function"?