首页 > 解决方案 > 如何使用 python tornado @gen.coroutine 和长时间运行的函数

问题描述

我有一个 Web 应用程序,它也在进行非常密集的数据处理。有些功能非常慢(想想几分钟)。

到现在为止,我的架构是为每个连接生成新的线程/进程,因此这些慢速功能不会阻塞其他用户。但这会消耗太多内存,并且不利于龙卷风架构。

所以我想知道这种问题是否有解决方案。我的代码如下所示:

# 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和不创建新线程/进程的情况下重构处理程序?

标签: pythonmultithreadingasynchronoustornado

解决方案


使用ThreadPoolExecutor(来自concurrent.futures包)在单独的线程中运行长时间运行的函数,而无需每次都启动一个新线程。

async def handler():
    await IOLoop.current().run_in_executor(None, really_slow_function)
    return "done"

如果你想准确控制有多少线程有资格运行这个函数,你可以创建自己的执行器并传递它而不是None.


推荐阅读