python - 如何始终并行运行 n 个进程,而不等待前 n 个进程完成?

标签 python python-3.x parallel-processing multiprocessing

我想要运行 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()

https://docs.python.org/2/library/multiprocessing.html

关于python - 如何始终并行运行 n 个进程,而不等待前 n 个进程完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55776020/

相关文章:

python - Pandas 数据框行的条件循环

java - 为什么不能并行减少流流?/流已经被操作或关闭

Python 等待一个内部有循环的函数

python - 列表上的 re.sub - python 3

python - 获取 bash 命令的结果并在 python 中使用它

python - 使用 RandomizedSearchCV 进行随机森林调整

python - python中的回文素数

python-3.x - 如何优化此 python 代码以对大输入进行排序?

r - devtools::test() 并行?

python - 删除字符串的隐藏部分时遇到问题