背景: Python 3.6.5、Django 1.10 我正在尝试使用 ThreadPoolExecutor 和 ProcessPoolExecutor 来减少响应时间,以加快我的 API 速度。添加示例代码:
from django import db
db.connections.close_all()
with ProcessPoolExecutor(max_workers=4) as executor:
executors_list.append(
executor.submit(self.get_investment_data_table, current=current)
)
executors_list.append(
executor.submit(self.get_scheme_wise_cashflow_sum, current=current)
)
executors_list.append(
executor.submit(self.get_scheme_wise_xirr, current=current)
)
executors_list.append(executor.submit(self.scheme_wise_transactions))
executors_list = list(executors_list)
all_investment_list = executors_list[0].result()
scheme_wise_cashflow_sum = executors_list[1].result()
scheme_wise_xirr = executors_list[2].result()
transactions = executors_list[3].result()
# club all 4 and return as response
问题: 在尝试 ThreadPoolExecutor 和 ProcessPoolExecutor 的不同功能时,我发现 Threadpool 工作正常,但是当我尝试 ProcessPoolExecutor 时,我收到此错误:
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
奇怪的是,api 调用成功了 2-3 次,之后就开始不断失败。响应大小约为 5 MB。所有底层函数都包含数据库调用和至少一定量的处理。我感到困惑的是,如果这是一个酸洗错误,那么代码从第一次开始就应该失败。
有人可以帮助我或为我指出如何调试和解决问题的正确方向吗?
对我来说,它有助于调用 ProcessPoolExecutor 检查它是否是主模块:
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=4) as executor:
... do your work here ...