【发布时间】:2020-05-29 21:55:33
【问题描述】:
我有一个 Web 应用程序也在进行非常密集的数据处理。 有些功能非常慢(想想几分钟)。
到目前为止,我的架构是为每个连接生成新的线程/进程,因此这些慢速功能不会阻塞其他用户。但这会消耗太多内存,而且不符合 tornado 架构。
所以我想知道这种问题是否有解决方案。 我的代码如下所示:
# 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 并且不创建新线程/进程的情况下重构处理程序?
【问题讨论】:
-
阻塞函数需要在单独的线程中运行。没有办法解决它。
标签: python multithreading asynchronous tornado