多处理和变量返回?

时间:2014-11-09 03:08:49

标签: python multiprocessing

我一直在用Python来对付多处理过程中的一天中的大部分时间,并且我已经设法取得了很小的进展 - 如果我的问题是重复或我的无知显而易见,我道歉 - 我道歉无法通过这种方式在其他任何地方找到它。

我正在寻找一种并行运行函数的方法,并将它们产生的任意内容返回给主脚本。

问题是:从多处理开始的Process()是否可以返回列表或其他任意变量类型?

例如,我想:

def 30_second_function():
    #pretend this takes 30 seconds to run
    return ["mango", "habanero", "salsa"]
#End 30_second_function()

def 5_second_function():
    #pretend this takes 5 seconds to run
    return {"beans": "8 oz", "tomato paste": "16 oz"}
#End 5_second_function()

p1 = multiprocessing.Process(target=30_second_function)
p1.start()
p2 = multiprocessing.Process(target=5_second_function)
p2.start()

#Somehow retrieve the list and the dictionary here.  p1.returned??

然后以某种方式访问​​30_second_function中的列表和5_second_function中的字典。这可能吗?我是以错误的方式解决这个问题吗?

1 个答案:

答案 0 :(得分:3)

Process本身并不提供获取返回值的方法。 To exchange data between processes, you need to use queue, pipe,共享内存,......:

import multiprocessing

def thirty_second_function(q):
    q.put(["mango", "habanero", "salsa"])

def five_second_function(q):
    q.put({"beans": "8 oz", "tomato paste": "16 oz"})

if __name__ == '__main__':
    q1 = multiprocessing.Queue()
    p1 = multiprocessing.Process(target=thirty_second_function, args=(q1,))
    p1.start()

    q2 = multiprocessing.Queue()
    p2 = multiprocessing.Process(target=five_second_function, args=(q2,))
    p2.start()

    print(q1.get())
    print(q2.get())

使用multiprocessing.pool.Pool替代方案:

import multiprocessing.pool

def thirty_second_function():
    return ["mango", "habanero", "salsa"]

def five_second_function():
    return {"beans": "8 oz", "tomato paste": "16 oz"}

if __name__ == '__main__':
    p = multiprocessing.pool.Pool()
    p1 = p.apply_async(thirty_second_function)
    p2 = p.apply_async(five_second_function)

    print(p1.get())
    print(p2.get())

或使用concurrent.futures modulealso available in standard library since Python 3.2+):

from concurrent.futures import ProcessPoolExecutor

def thirty_second_function():
    return ["mango", "habanero", "salsa"]

def five_second_function():
    return {"beans": "8 oz", "tomato paste": "16 oz"}

if __name__ == '__main__':
    with ProcessPoolExecutor() as e:
        p1 = e.submit(thirty_second_function)
        p2 = e.submit(five_second_function)
    print(p1.result())
    print(p2.result())