我想要运行 50 种不同的方法。我有 10 个可用的 cpu,所以我只能同时运行 10 个进程。所以我运行了 5 次。然而,问题是前 10 个进程必须完成才能启动后 10 个进程,这会增加完成所需的时间。我想要的是,一旦 9 个进程运行,一个新进程就应该启动并始终运行 10 个进程。
我将 50 个类分为 5 个不同的组并运行。
组1 = [类(class)1,类(class)2...] group2 = [class11, class12..]
组 = [组 1, 组 2, ..., 组 5]
for group in groups:
threads = []
for x in group:
threads.append(mp.Process(target= x().method(), args= (b,)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
最佳答案
您应该创建一个进程池并使用 apply_async 方法:
from multiprocessing import Pool
pool = Pool(processes=10) # start 10 worker processes
for arg in args:
pool.apply_async(yourFunc, args = (arg, ))
pool.close()
pool.join()
关于python - 如何始终并行运行 n 个进程,而不等待前 n 个进程完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55776020/