简体   繁体   English

Python 2.7多处理无需使用缓冲池即可获得处理结果

[英]Python 2.7 multiprocessing get process result whithout using pool

How can I get the result from my process without using a pool ? 在不使用池的情况下如何从过程中获得结果?

(I'm willing to conserve an eye on the progression: (我愿意留意进展情况:

(print "\r",float(done)/total,"%",)

which can't be done using a pool as far I know) 据我所知,这无法使用游泳池来完成)

def multiprocess(function, argslist, ncpu):
    total = len(argslist)
    done = 0
    jobs = []
    while argslist != []:
        if len(mp.active_children()) < ncpu:
            p = mp.Process(target=function,args=(argslist.pop(),))
            jobs.append(p)
            p.start()
            done+=1
            print "\r",float(done)/total,"%",
    #get results here
    for job in jobs:
        job.get_my_result()???

The processes are really short (<0.5 seconds) but I have around 1 million of them. 该过程确实很短(<0.5秒),但是我大约有100万。

I saw this thread Can I get a return value from multiprocessing.Process? 我看到了这个线程我可以从multiprocessing.Process获取返回值吗? I tried to reproduce it but I couldn't make it work properly. 我试图重现它,但无法使其正常工作。

At your entire disposal for any further information. 供您进一步了解。

This question may be considered as a duplicate but anyway here is the solution to my problem: 这个问题可以被认为是重复的,但无论如何,这是我的问题的解决方案:

def multiprocess(function, argslist, ncpu):
    total = len(argslist)
    done = 0
    result_queue = mp.Queue()
    jobs = []
    while argslist != [] and done<10 :
        if len(mp.active_children()) < ncpu:
            p = mp.Process(target=function,args=(result_queue, argslist.pop(),))
            jobs.append(p)
            p.start()
            done+=1
            print "\r",float(done)/total,"%",
    #get results here
    res = [result_queue.get() for p in jobs]
    print res

and I had to change as well the 我也不得不改变

return function_result

into

result_queue.put(function_result)

The easiest way should be a queue that is passed as argument to your function. 最简单的方法应该是将队列作为参数传递给函数。 The results of that function can be put into that queue and later on you can iterate over that queue to collect all the results or process it as soon as a result arrives. 该函数的结果可以放入该队列中,以后您可以遍历该队列以收集所有结果或在结果到达后立即对其进行处理。 However, it only works when the you can work with "unordered" results. 但是,仅当您可以使用“无序”结果时,它才起作用。 See the Python documentation for details: Examples for Multiprocessing and Queues 有关详细信息,请参见Python文档: 多处理和队列示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM