[英]How to use python tornado @gen.coroutine with long running functions
我有一个 web 应用程序,它也在进行非常密集的数据处理。 有些功能非常慢(想想几分钟)。
到现在为止,我的架构是为每个连接生成新的线程/进程,因此这些慢速功能不会阻塞其他用户。 但这消耗了太多 memory 并且它不利于龙卷风架构。
所以我想知道这种问题是否有解决方案。 我的代码如下所示:
# code that is using to much memory because of the new threads being spawned
def handler():
thread = Thread(target = really_slow_function)
thread.start()
thread.join()
return "done"
def really_slow_function():
# this is an example of an intensive function
# which should be treated as a blackbox
sleep(100)
return "done"
重构后,我有以下代码:
#code that doesn't scale because all the requests are block on that one slow request.
@gen.coroutine
def handler():
yield really_slow_function()
raise gen.Return("done")
def really_slow_function():
# this is an example of an intensive function
# which should be treated as a blackbox
sleep(100)
return "done"
此重构的问题在于,tornado 服务器阻塞了really_slow_function
,同时无法为其他请求提供服务。
所以问题是:有没有一种方法可以在不触及really_slow_function
并且不创建新线程/进程的情况下重构处理程序?
使用ThreadPoolExecutor
(来自concurrent.futures
包)在单独的线程中运行长时间运行的 function,而无需每次都启动新线程。
async def handler():
await IOLoop.current().run_in_executor(None, really_slow_function)
return "done"
如果您想准确控制有多少线程有资格运行此 function,您可以创建自己的执行程序并传递它而不是None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.