Python的多处理.Pool产生了新的进程

时间:2014-08-28 21:44:25

标签: python multiprocessing

我有一个关于多处理模块的简单问题。我正在使用multiprocessing.Pool的map()函数来加速在我的本地机器上执行自编代码。但是,这个代码是在一个迭代循环中运行的,我发现在我的机器中每次迭代循环都会产生额外的Python进程。 (这是一个问题,因为系统慢慢停止)。这是一个简单的例子:

from multiprocessing import Pool
import os

nthreads = 2
for ii in xrange(5):
    pool = Pool(processes=nthreads)  # (in my code, Pool is inside a pickleable function.)
    runningProcesses = os.popen('ps | grep ython').readlines()
    nproc = len(runningProcesses)
    print "After iteration %i there were %i Python processes running!" % (ii, nproc)

输出结果为:

After iteration 0 there were 5 Python processes running!
After iteration 1 there were 7 Python processes running!
After iteration 2 there were 9 Python processes running!
After iteration 3 there were 11 Python processes running!
After iteration 4 there were 13 Python processes running!

我应该如何安排我的代码以避免产生许多新的Python进程?我正在运行Python 2.7.6,它具有多处理v0.70a1,并且运行在运行OSX 10.8.5的4核MacBook Pro上。

2 个答案:

答案 0 :(得分:0)

pool = Pool(processes=nthreads)置于for循环

之上

答案 1 :(得分:0)

正如评论中所讨论的那样 - 池中的工作进程没有被关闭/加入,因此它们永远不会终止。这里的首要答案显示了当您不再需要它时如何清理池:Python multiprocessing pool, join; not waiting to go on?

作为旁注,如果您正在创建大量工作人员并使用它们来执行非常短/快速的工作,那么您可能会发现性能受到影响 - 操作系统创建和销毁流程的开销很大。如果是这种情况,那么您应该考虑在整个应用程序中使用单个池。