[英]python multiprocessing pool: how can I know when all the workers in the pool have finished?
我在 python 中運行一個多處理池,我有大約 2000 個任務,通過池映射到 24 個工作人員。 每個任務根據一些數據分析和網絡服務創建一個文件。
當池中的所有任務都完成后,我想運行一個新任務。 我如何知道池中的所有進程何時完成?
您希望使用join
方法 ,該方法會停止主進程線程向前移動,直到所有子進程結束:
阻止調用線程,直到調用其join()方法的進程終止或直到發生可選超時。
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
processes = []
for i in range(10):
p = Process(target=f, args=('bob',))
processes.append(p)
for p in processes:
p.start()
p.join()
# only get here once all processes have finished.
print('finished!')
編輯:
要使用join
與池
pool = Pool(processes=4) # start 4 worker processes
result = pool.apply_async(f, (10,)) # do some work
pool.close()
pool.join() # block at this line until all processes are done
print("completed")
您可以使用AsyncResult
對象的wait()
方法(這是apply_async
返回的內容)。
import multiprocessing
def create_file(i):
open(f'{i}.txt', 'a').close()
if __name__ == '__main__':
# The default for n_processes is the detected number of CPUs
with multiprocessing.Pool() as pool:
# Launch the first round of tasks, building a list of AsyncResult objects
results = [pool.apply_async(create_file, (i,)) for i in range(50)]
# Wait for every task to finish
[result.wait() for result in results]
# {start your next task... the pool is still available}
# {when you reach here, the pool is closed}
即使您計划再次使用您的池並且不想關閉它,此方法也有效,正如@dano 指出的那樣。 例如,您可能需要為算法的下一次迭代保留它。 完成后一定要關閉它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.