Python的multiprocessing.Pool生成新进程
我有一个关于多进程模块的简单问题。我正在使用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,里面有multiprocessing v0.70a1,并且我是在一台运行OSX 10.8.5的四核MacBook Pro上。
2 个回答
0
把 pool = Pool(processes=nthreads)
这行代码放到 for
循环的上面。
0
在评论中提到,池中的工作进程没有被关闭或合并,所以它们一直在运行,永远不会结束。这里的最佳答案展示了当你不再需要这个池时,如何进行清理:Python多进程池,合并;不等待继续吗?
另外,如果你创建了很多工作进程,并用它们来执行非常短小的任务,你可能会发现性能会下降——因为操作系统在创建和销毁进程时会有额外的开销。如果是这种情况,你应该考虑在整个应用中使用一个单一的池。