Python 2.7 multiprocessing 不使用池获取处理结果

Python 2.7 multiprocessing get process result whithout using pool

如何在不使用池的情况下从我的过程中获取结果?

(我愿意关注进度:

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

据我所知,使用池无法完成)

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()???

流程真的很短(<0.5 秒),但我有大约 100 万个流程。

我看到了这个帖子Can I get a return value from multiprocessing.Process?我试图重现它,但我无法使其正常工作。

如有任何进一步信息,请随时为您服务。

最简单的方法应该是将队列作为参数传递给您的函数。该函数的结果可以放入该队列,稍后您可以遍历该队列以收集所有结果或在结果到达时立即处理它。但是,它仅在您可以使用 "unordered" 结果时才有效。有关详细信息,请参阅 Python 文档:Examples for Multiprocessing and Queues

这个问题可能被认为是重复的,但无论如何这是我的问题的解决方案:

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

而且我还必须更改

return function_result

进入

result_queue.put(function_result)