我想知道在多处理模块中是否有一个本机实现,它允许我将正在运行的进程存储在基于列表的结构中,并且每当进程完成执行时,它就会自动从列表中删除。
在代码中,它看起来如下所示:
from multiprocessing import process
pool = [] # This data structure needs to prune non-running processes
class A(Process):
def run():
pass
for i in range(0, 10):
worker = A().start()
pool.append(worker)
# So if I want to iterate the pool now, It should only contain the alive processes处理这一问题的另一种方法是保存一本字典:
pool = {
processId: processObject
}然后使用psutil获取活动进程ids:
current_process = psutil.Process()
children = current_process.children(recursive=False)然而,当进程死后,字典中的对象的大小是多少?
发布于 2018-11-09 00:12:32
我不认为这样一个假设的自更新结构会是一个好主意,对于同一个reason,您不应该在迭代列表时修改它。在遍历池时,进程可能会被删除。
为了安全地遍历它,您需要一个快照,这将使这样一个结构的全部工作变得毫无意义。当您需要更新池列表时,最好通过以下方法显式地这样做:
pool[:] = [p for p in pool if p.is_alive()] # p are your processes
或者,如果您想要所有进程范围内的、活动的子进程,而不仅仅是自定义池中的子进程:
[p for p in multiprocessing.active_children()]
当然,您可以将它放在函数或方法中的某个位置,并在需要实际池列表时调用它。进程有一个pid属性,所以您不需要只为获取进程ids而使用psutil。
https://stackoverflow.com/questions/53207826
复制相似问题