线程池不释放内存?

ThreadPool not releasing memory?

当使用 Python 的 ThreadPool 并行化 CPU 密集型任务时,工作人员使用的内存似乎被累积而不是释放。我试图简化问题:

import numpy as np
from multiprocessing.pool import ThreadPool

def worker(x):
    # Bloat the memory footprint of this function
    a = x ** x
    b = a + x
    c = x / b
    return hash(c.tobytes())   

tasks = (np.random.rand(1000, 1000) for _ in range(500))

with ThreadPool(4) as pool:
    for result in pool.imap(worker, tasks):
        assert result is not None

当 运行 这个片段时,可以很容易地观察到 Python 使用的内存占用量的巨大跳跃。但是我希望这与

具有几乎相同的行为
for task in tasks:
    assert worker(task) is not None

其内存成本可以忽略不计。

我如何修改代码片段以使用 ThreadPoolworker 函数应用于每个数组?

原来解释很简单。修改示例以仅在 worker 内部创建随机数组将解决问题:

def worker(x):
    x = x()
    # Bloat the memory footprint of this function
    a = x ** x
    b = a + x
    c = x / b
    return hash(c.tobytes())

tasks = (lambda: np.random.rand(1000, 1000) for _ in range(500))

似乎 ThreadPools.imap 会在内部将生成器 tasks 变成列表或类似的东西。这当然需要一次将所有 500 个随机数组存储在内存中。