等待所有进程完成 python
Wait for all processes to finish python
这个问题已经被问过很多次了,但我找不到符合我的具体设置的答案。
我有一个使用多处理的脚本。这是一个简化得多的示例:
from multiprocessing import Pool
def my_function(arg1,arg2):
print(arg1,arg2)
with Pool(processes=5) as pool:
pool.starmap(function, [(arg1,arg2),(arg1,arg2)])
pool.join()
print("should only run once all processes are finished")
我希望此时关闭池并继续正常的单一处理功能。我认为上下文管理器会处理池的关闭,而 .join() 会确保它只在所有进程完成后关闭。但我看到的行为表明,在所有进程完成之前,程序 运行 超出了上下文管理器。我现在还需要做些什么吗?
此外,在这种情况下,分配了 5 个进程,但只有 2 个参数元组传递给了函数。在这种情况下,多余的 3 个进程会做什么?
Python-V 3.9
您需要在 pool.join()
之前调用 pool.close()
。
您可以通过调用当前进程的 _identity
变量来查看哪个进程 运行 函数。最后可以通过调用当前进程的name
确保只有主进程是运行。
由于调用次数少于进程数,其余进程只是做通常的 OS 事情。
from multiprocessing import Pool, current_process
def my_function(arg1,arg2):
rank = f'running on process: {current_process()._identity[0]}'
print(rank, arg1,arg2)
arg1 = 'arg1'
arg2 = 'arg2'
with Pool(processes=5) as pool:
pool.starmap(my_function, [(arg1,arg2),(arg1,arg2)])
pool.close()
pool.join()
print(current_process().name)
print("should only run once all processes are finished")
输出:
running on process: 1 arg1 arg2
running on process: 2 arg1 arg2
MainProcess
should only run once all processes are finished
这个问题已经被问过很多次了,但我找不到符合我的具体设置的答案。
我有一个使用多处理的脚本。这是一个简化得多的示例:
from multiprocessing import Pool
def my_function(arg1,arg2):
print(arg1,arg2)
with Pool(processes=5) as pool:
pool.starmap(function, [(arg1,arg2),(arg1,arg2)])
pool.join()
print("should only run once all processes are finished")
我希望此时关闭池并继续正常的单一处理功能。我认为上下文管理器会处理池的关闭,而 .join() 会确保它只在所有进程完成后关闭。但我看到的行为表明,在所有进程完成之前,程序 运行 超出了上下文管理器。我现在还需要做些什么吗?
此外,在这种情况下,分配了 5 个进程,但只有 2 个参数元组传递给了函数。在这种情况下,多余的 3 个进程会做什么?
Python-V 3.9
您需要在 pool.join()
之前调用 pool.close()
。
您可以通过调用当前进程的 _identity
变量来查看哪个进程 运行 函数。最后可以通过调用当前进程的name
确保只有主进程是运行。
由于调用次数少于进程数,其余进程只是做通常的 OS 事情。
from multiprocessing import Pool, current_process
def my_function(arg1,arg2):
rank = f'running on process: {current_process()._identity[0]}'
print(rank, arg1,arg2)
arg1 = 'arg1'
arg2 = 'arg2'
with Pool(processes=5) as pool:
pool.starmap(my_function, [(arg1,arg2),(arg1,arg2)])
pool.close()
pool.join()
print(current_process().name)
print("should only run once all processes are finished")
输出:
running on process: 1 arg1 arg2
running on process: 2 arg1 arg2
MainProcess
should only run once all processes are finished