澄清Python的`multiprocessing.Pool`的`processes`参数

时间:2014-06-19 03:15:12

标签: python multiprocessing

我的问题是,如果我执行[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]

1 个答案:

答案 0 :(得分:3)

multiprocessing.Pool永远不会比创建时指定的数字并行运行更多进程。相反,它会立即生成您指定的多个进程,并使它们保持运行直到池关闭/加入。因此,在您的情况下,Pool总是正好运行四个进程,即使它们都没有做任何工作。如果您为池提供了8个工作项,则前四个将立即开始并行执行,而接下来的四个将排队。只要其中一个工作进程完成运行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]
相关问题