Fer*_*yev 1 python parallel-processing multiprocessing python-3.x
我有 50 种不同的方法想要运行。我有 10 个可用的 cpu,所以我只能同时运行 10 个进程。所以我运行了 5 次。然而,问题是前 10 个进程必须完成才能启动后 10 个进程,这会增加完成所需的时间。我想要的是,一旦 9 个进程运行,一个新进程就应该启动并始终运行 10 个进程。
我将 50 个班级分成 5 个不同的小组并运行。
group1 = [class1, class2...] 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()
Run Code Online (Sandbox Code Playgroud)
您应该创建一个进程池并使用 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()
Run Code Online (Sandbox Code Playgroud)
https://docs.python.org/2/library/multiprocessing.html