以下代码总是给我错误
OSError: [Errno 24] Too many open files
当执行的进程达到 508 个时,这意味着每个进程都会打开两个文件描述符,然后我就达到了系统的限制:
from multiprocessing import Process
def do_job(task):
print("Task no " + str(task))
def main():
number_of_processes = 1000
processes = []
for i in range(number_of_processes):
p = Process(target=do_job, args=(i,))
processes.append(p)
# creating processes
for p in processes:
p.start()
p.join()
return True
if __name__ == "__main__":
main()
如果我在 vs code 终端上尝试相同的代码,那么它会毫无问题地完成。我查看了许多类似的在线线程,但尚未找到可行的解决方案。
问题在于该列表仍然保留对每个进程的实时引用。从列表中弹出进程解决了问题:
from multiprocessing import Process
def do_job(task):
print("Task no " + str(task))
def main():
number_of_processes = 1000
processes = []
for i in range(number_of_processes):
p = Process(target=do_job, args=(i,))
processes.append(p)
# creating processes
for i in range(number_of_processes):
p = processes.pop(0)
p.start()
p.join()
return True