How to retrieve multiple values returned of a function called through multiprocessing.Process

浪子不回头ぞ 提交于 2020-06-24 11:29:32

问题


I have a scenario like this :

for each in content :
     pdf_output,job_id=createpdf(each)
     if pdf_output : 
        pdf_output = pdf_output + pdf_output

I am trying to parallelize the whole process .Something like this

 jobs=[]
    for each in content : 
       jobs.append(multiprocessing.Process(target=self.createpdf, args=(content)))

    for each in jobs :
         jobs.start()
    for each in jobs :
         jobs.join()

How do I sensibly do the task of

if pdf_output : 
            pdf_output = pdf_output + pdf_output

For each job ? How do I retrieve the 2 retun values sent by createpdf and work on it ? I think multiprocessing.Queue is a clue , but how do I implement this ?


回答1:


You do not need queues for such a simple task. I would recommend to use pools. The Pool.map method can apply a function to a series of values in parallel:

import multiprocessing
def createpdf(data):
    return ("This is my pdf data: %s\n" % data, 0)


data = [ "My data", "includes", "strings and", "numbers like", 42, "and", 3.14]
number_of_processes = 5
results = multiprocessing.Pool(number_of_processes).map(createpdf, data)
outputs = [result[0] for result in results]
pdfoutput = "".join(outputs)


来源:https://stackoverflow.com/questions/10797484/how-to-retrieve-multiple-values-returned-of-a-function-called-through-multiproce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!