背景
在有200W的任務需要取抓取的時候,目前采用的是線程池去抓取,最終導致內存暴漲。
原因
Threadpoolexcutor默認使用的是無界隊列,如果消費任務的速度低於生產任務,那么會把生產任務無限添加到無界隊列中。導致內存被占滿
解決方案
修改無界隊列為有界隊列
import queue
from concurrent.futures import ThreadPoolExecutor
class ThreadPoolExecutor(ThreadPoolExecutor):
"""
重寫線程池修改隊列數
"""
def __init__(self, max_workers=None, thread_name_prefix=''):
super().__init__(max_workers, thread_name_prefix)
# 隊列大小為最大線程數的兩倍
self._work_queue = queue.Queue(self._max_workers * 2)