在这一天的大部分时间里,我一直在与Python中的Multiprocessing打交道,而我几乎没有取得什么进展--如果我的问题是重复的,或者我的无知是显而易见的,我很抱歉--我找不到以这种方式问其他地方的问题。
我正在寻找一种并行运行函数的方法,并将它们生成的任意内容返回到主脚本。
问题是:从多重处理开始的进程()能否返回列表或其他任意变量类型?
例如,我想:
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访问字典。这个是可能的吗?我是不是走错路了?
发布于 2014-11-09 03:14:59
Process本身并不提供获取返回值的方法。若要在进程之间交换数据,需要使用队列、管道。,共享内存.:
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())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())或使用模块 (也可在标准库中使用,因为Python):
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())https://stackoverflow.com/questions/26824552
复制相似问题