使用multiprocessing.Process并发进程数最多
我有Python
代码:
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
for i in range(0, MAX_PROCESSES):
p = Process(target=f, args=(i,))
p.start()
运行良好。但是,MAX_PROCESSES
是变量,可以是1
和之间的任何值512
。由于我仅在具有8
内核的机器上运行此代码,因此我需要确定是否有可能限制允许同时运行的进程数。我已经调查过multiprocessing.Queue
,但看起来并不需要我的东西-
也许是我对文档的解释不正确。
有没有一种方法可以限制同时multiprocessing.Process
运行的数量?
-
可能最明智的做法是
multiprocessing.Pool
根据系统上可用的最大内核数生成一个工作进程池,然后在内核可用时基本上提供任务。标准文档(http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-
workers)中的示例显示,您还可以手动设置核数:from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': pool = Pool(processes=4) # start 4 worker processes result = pool.apply_async(f, [10]) # evaluate "f(10)" asynchronously print result.get(timeout=1) # prints "100" unless your computer is *very* slow print pool.map(f, range(10)) # prints "[0, 1, 4,..., 81]"
而且
multiprocessing.cpu_count()
,如果代码中需要的话,也很容易知道有一种方法可以计算给定系统上的内核数。编辑:这是一些看起来适合您的特定情况的代码草案:
import multiprocessing def f(name): print 'hello', name if __name__ == '__main__': pool = multiprocessing.Pool() #use all available cores, otherwise specify the number you want as an argument for i in xrange(0, 512): pool.apply_async(f, args=(i,)) pool.close() pool.join()