multiprocessing returns "too many open files" 但使用 `with...as` 修复了它。为什么?
multiprocessing returns "too many open files" but using `with...as` fixes it. Why?
我使用 this answer 是为了 运行 在 Linux 框的 Python 中使用多处理并行命令。
我的代码做了类似的事情:
import multiprocessing
import logging
def cycle(offset):
# Do stuff
def run():
for nprocess in process_per_cycle:
logger.info("Start cycle with %d processes", nprocess)
offsets = list(range(nprocess))
pool = multiprocessing.Pool(nprocess)
pool.map(cycle, offsets)
但是我收到了这个错误:OSError: [Errno 24] Too many open files
因此,代码打开了太多的文件描述符,即:它启动了太多的进程并且没有终止它们。
我修复了它,用这些行替换了最后两行:
with multiprocessing.Pool(nprocess) as pool:
pool.map(cycle, offsets)
但我不知道为什么这些行修复了它。
with
下面发生了什么?
它是上下文管理器。使用 with 可确保您正确打开和关闭文件。要详细了解这一点,我推荐这篇文章 https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/
您在循环中创建新进程,然后在完成后忘记关闭它们。结果,您有太多打开的进程。这是个坏主意。
您可以通过使用自动调用 pool.terminate
的上下文管理器或您自己手动调用 pool.terminate
来解决此问题。或者,为什么不在循环外创建一个池 一次,然后将任务发送到循环内的进程?
pool = multiprocessing.Pool(nprocess) # initialise your pool
for nprocess in process_per_cycle:
...
pool.map(cycle, offsets) # delegate work inside your loop
pool.close() # shut down the pool
有关详细信息,您可以仔细阅读 multiprocessing.Pool
文档。
当您也使用 numpy.load 时可能会发生这种情况,请确保也关闭这些文件,或者避免使用它并使用 pickle 或 torch.save torch.load 等
我已经终止并关闭了池,但是文件描述符的数量有限制,我将我的 ulimit 从 1024
更改为 4096
并且它起作用了。程序如下:
检查:
ulimit -n
我将其更新为 4096 并且有效。
ulimit -n 4096
我使用 this answer 是为了 运行 在 Linux 框的 Python 中使用多处理并行命令。
我的代码做了类似的事情:
import multiprocessing
import logging
def cycle(offset):
# Do stuff
def run():
for nprocess in process_per_cycle:
logger.info("Start cycle with %d processes", nprocess)
offsets = list(range(nprocess))
pool = multiprocessing.Pool(nprocess)
pool.map(cycle, offsets)
但是我收到了这个错误:OSError: [Errno 24] Too many open files
因此,代码打开了太多的文件描述符,即:它启动了太多的进程并且没有终止它们。
我修复了它,用这些行替换了最后两行:
with multiprocessing.Pool(nprocess) as pool:
pool.map(cycle, offsets)
但我不知道为什么这些行修复了它。
with
下面发生了什么?
它是上下文管理器。使用 with 可确保您正确打开和关闭文件。要详细了解这一点,我推荐这篇文章 https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/
您在循环中创建新进程,然后在完成后忘记关闭它们。结果,您有太多打开的进程。这是个坏主意。
您可以通过使用自动调用 pool.terminate
的上下文管理器或您自己手动调用 pool.terminate
来解决此问题。或者,为什么不在循环外创建一个池 一次,然后将任务发送到循环内的进程?
pool = multiprocessing.Pool(nprocess) # initialise your pool
for nprocess in process_per_cycle:
...
pool.map(cycle, offsets) # delegate work inside your loop
pool.close() # shut down the pool
有关详细信息,您可以仔细阅读 multiprocessing.Pool
文档。
当您也使用 numpy.load 时可能会发生这种情况,请确保也关闭这些文件,或者避免使用它并使用 pickle 或 torch.save torch.load 等
我已经终止并关闭了池,但是文件描述符的数量有限制,我将我的 ulimit 从 1024
更改为 4096
并且它起作用了。程序如下:
检查:
ulimit -n
我将其更新为 4096 并且有效。
ulimit -n 4096