我在这个小 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/