Python:多处理无法完成作业

Dol*_*ids 5 python pool multiprocessing python-multiprocessing

我将python 2.7与multiprocessing :: Pool一起使用以并行运行作业

我简化了下面的示例,但这是它的主要要旨。

它将使用该apply_async()函数为我的字典中的每个人创建一个文件。但是,当我检查文件是否正确创建时,我注意到有时文件没有创建。

现在我想我在使用multiprocessing :: Pool的方式上做错了

有什么建议吗?

import os
from multiprocessing import Pool

def outputFile(person):
    ofh=open(person+'.txt','w')
    ofh.write('test\n')
    ofh.close()

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputFile,args(person))
pool.close()
pool.join()
for person in person_dict:
    print os.path.isfile(person+'.txt')
Run Code Online (Sandbox Code Playgroud)
True
True
False
True
Run Code Online (Sandbox Code Playgroud)

neu*_*ite 1

这可能与 person_dict 的内容有关吗?

我修改了你的代码并运行了几次。他们都产生了预期的结果。

这是我修改并测试的代码:

import os
from multiprocessing import Pool

def outputfile(person):
    with open(person+'.txt','w') as ofh:
        ofh.write('test\n')

person_dict = {'a': 'a', 'b': 'b', 'c':'c', 'd':'d'}

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputfile, (person))
pool.close()
pool.join()

for person in person_dict:
    print(os.path.isfile(person+'.txt'))
Run Code Online (Sandbox Code Playgroud)