使用multiprocessing.Pool时打开了太多文件
我有一个Python脚本,它使用multiprocessing.Pool来分别处理很多文件。我的电脑通常最多能用8个CPU核心。我的问题是,运行一段时间后,我总是会遇到“IOError: [Errno 24] 打开的文件太多了”的错误。每个子进程会打开几个文件来读取,这些文件是用file.open()打开的。然后,这些文件的句柄会被传递给多个函数来获取数据。在每个子进程结束时,这些文件会用file.close()关闭。我也试过使用with语句,但问题依然没有解决。有没有人知道问题出在哪里?我在网上查了很多,但没有找到答案。我确实在关闭文件,而且函数也正常返回,那么为什么文件句柄还会存在呢。
我的设置是Mac 10.5,使用Python 2.6
谢谢
Ogan
from custom import func1, func2
# func1 and func2 only seek, read and return values form the file
# however, they do not close the file
import multiprocessing
def Worker(*args):
f1 = open("db1.txt")
f2 = open("db2.txt")
for each in args[1]:
# do many stuff
X = func1(f1)
Y = func2(f2)
f1.close()
f2.close()
return
Data = {1:[2], 2:[3]}
JobP= multiprocessing.Pool(8)
jobP.map_async(Worker, Data.items())
jobP.close()
jobP.join()
2 个回答
0
要在Yosemite(OS X 10.10)中更改打开文件的数量限制:
sudo launchctl limit maxfiles [number-of-files] unlimited
0
很可能是你的操作系统限制了可以打开的文件数量。想了解更多信息,可以查看这个链接:如何在Linux中更改打开文件的限制?。我个人比较喜欢修改 /etc/security/limits.conf 这个设置。