不断 运行 工人池
Constantly running Pool of workers
我正在使用 multiprocessor.Pool
并行处理一些文件。代码等待接收文件,然后使用 Pool.apply_async
将该文件发送给工作人员,然后工作人员处理该文件。
此代码应该始终是 运行,因此我永远不会关闭池。然而,这会导致池随着时间的推移消耗大量内存。
代码是这样的:
if __name__ == "__main__":
with Pool(processes=PROCESS_COUNT) as pool:
while True:
f = wait_for_file()
pool.apply_async(process_file, (f,))
如何在不关闭池的情况下防止内存使用率过高?
是的,如果您分配资源但不释放它们,无论是 spawned processes 的数量还是只是(一大块)内存,您机器上用于其他任务的资源都会减少,直到您或者您的系统自愿或强制取消分配它们。
您可能想对 Pool
使用 maxtasksperchild
参数来尝试杀死奴隶,例如如果他们分配内存而你在某处发生泄漏,那么你至少可以节省一些资源。
Note: Worker processes within a Pool typically live for the complete duration of the Pool’s work queue. A frequent pattern found in other systems (such as Apache, mod_wsgi, etc) to free resources held by workers is to allow a worker within a pool to complete only a set amount of work before being exiting, being cleaned up and a new process spawned to replace the old one. The maxtasksperchild argument to the Pool exposes this ability to the end user.
或者,不要推出自己的 Pool
实现,因为在你实现之前,它会出现错误,你会不必要地浪费时间。 而是使用例如Celery(教程)希望它甚至可以测试你可能会花费比必要更多时间的讨厌的角落案例。
或者,如果您想进行一些试验,here is a similar question 它提供了自定义从属池管理的步骤。
我正在使用 multiprocessor.Pool
并行处理一些文件。代码等待接收文件,然后使用 Pool.apply_async
将该文件发送给工作人员,然后工作人员处理该文件。
此代码应该始终是 运行,因此我永远不会关闭池。然而,这会导致池随着时间的推移消耗大量内存。
代码是这样的:
if __name__ == "__main__":
with Pool(processes=PROCESS_COUNT) as pool:
while True:
f = wait_for_file()
pool.apply_async(process_file, (f,))
如何在不关闭池的情况下防止内存使用率过高?
是的,如果您分配资源但不释放它们,无论是 spawned processes 的数量还是只是(一大块)内存,您机器上用于其他任务的资源都会减少,直到您或者您的系统自愿或强制取消分配它们。
您可能想对 Pool
使用 maxtasksperchild
参数来尝试杀死奴隶,例如如果他们分配内存而你在某处发生泄漏,那么你至少可以节省一些资源。
Note: Worker processes within a Pool typically live for the complete duration of the Pool’s work queue. A frequent pattern found in other systems (such as Apache, mod_wsgi, etc) to free resources held by workers is to allow a worker within a pool to complete only a set amount of work before being exiting, being cleaned up and a new process spawned to replace the old one. The maxtasksperchild argument to the Pool exposes this ability to the end user.
或者,不要推出自己的 Pool
实现,因为在你实现之前,它会出现错误,你会不必要地浪费时间。 而是使用例如Celery(教程)希望它甚至可以测试你可能会花费比必要更多时间的讨厌的角落案例。
或者,如果您想进行一些试验,here is a similar question 它提供了自定义从属池管理的步骤。