并行独立过程

时间:2014-01-07 18:00:01

标签: python loops parallel-processing

我想在一个循环中启动几个进程,但由于它们要完成很长时间,我认为并行运行它们会更好。所有这些过程都是独立的,即它们不依赖于彼此的结果。 这是一个小例子,说明了我正在处理的循环类型:

inDir = '/path/to/your/dir/'
inTxtList = ['a.txt','b.txt','c.txt','d.txt','e.txt']
for i in inTxtList:
    myfile = open(i,'w')
    myfile.write("This is a text file written in python\n")
    myfile.close()

我已经尝试了multiprocessing包并提出以下代码:

import multiprocessing

def worker(num):
    """thread worker function"""
    myfile = open(num,'w')
    myfile.write("This is my first text file written in python\n")
    myfile.close()
    return

if __name__ == '__main__':
    jobs = []
    for i in inTxtList:
        p = multiprocessing.Process(target=worker, args=(inDir+i,))
        jobs.append(p)
        p.start()
        p.join()

它确实有效,但我不知道如何设定工人数量。你能帮帮我吗?

1 个答案:

答案 0 :(得分:3)

使用multiprocessing.Pool.map。您可以在创建processes对象时指定Pool参数来指定工作器数:

import os
import multiprocessing

def worker(num):
    with open(num, 'w') as f:
        f.write("This is my first text file written in python\n")

if __name__ == '__main__':
    number_of_workers = 4
    pool = multiprocessing.Pool(processes=number_of_workers)
    pool.map(worker, [os.path.join(inDir, i) for i in inTxtList])
    pool.close()
    pool.join()

BTW,使用os.path.join而不是手动连接路径组件。