【问题标题】:Clarification on the `processes` argument for Python's `multiprocessing.Pool`澄清 Python 的 `multiprocessing.Pool` 的 `processes` 参数
【发布时间】:2014-06-19 11:35:04
【问题描述】:

我的问题是如果我执行[pool.apply_async(myfunc, args=(y,)) for i in range(8)] 如下所示,并且我使用多个进程初始化Pool,例如这里4
这是否意味着每个函数调用都在 4 个进程上并行运行,而我也在并行运行 8 个函数调用,所以 4x8 = 32 个进程,还是它运行 4 次 1 函数调用,等到它们完成然后运行另一个4 个函数调用?

import multiprocessing
pool = multiprocessing.Pool(processes=4)
results = [pool.apply_async(myfunc, args=(i,)) for i in range(8)]
results = [res.get() for res in results]

【问题讨论】:

    标签: python multiprocessing


    【解决方案1】:

    multiprocessing.Pool 永远不会并行运行比您在创建时指定的数量更多的进程。相反,它会立即生成您指定的多个进程,并让它们一直运行,直到池关闭/加入。因此,在您的情况下,Pool始终运行恰好四个进程,即使它们都没有做任何工作。如果为池分配八个工作项,前四个将立即开始并行执行,而接下来的四个将排队。一旦其中一个工作进程完成运行myfunc,第一个排队的项目将开始由现在空闲的工作进程处理。

    如果你运行这个例子,你可以自己看到:

    def myfunc(num):
        print("in here %s" % num)
        time.sleep(2)
        print("done with %s" % num)
        return num+2
    
    if __name__ == "__main__":
        pool = multiprocessing.Pool(4)
        results = [pool.apply_async(myfunc, args=(i,)) for i in range(8)]
        results = [res.get() for res in results]
        print results
    

    输出:

    in here 0
    in here 1
    in here 2
    in here 3
    <2 second pause>
    done with 0
    done with 3
    done with 1
    in here 4
    in here 5
    in here 6
    done with 2
    in here 7
    <2 second pause>
    done with 6
    done with 7
    done with 4
    done with 5
    [2, 3, 4, 5, 6, 7, 8, 9]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2018-09-28
      • 2021-07-17
      • 2022-12-14
      • 1970-01-01
      • 2020-07-30
      相关资源
      最近更新 更多