获取python中多处理函数的返回值

时间:2016-06-17 05:03:34

标签: python python-multithreading python-multiprocessing

我有两个并行运行的函数,每个函数都返回一个值。我需要等待两个函数完成,然后处理它们的返回。我怎么能在python中实现这一点。假设

def fun1():
   #do some calculation#
   return val1

def fun2():
   #do some calculation#
   return val2

我希望fun1和fun2并行运行,然后需要计算

valsum = val1+val2

1 个答案:

答案 0 :(得分:7)

使用concurrent.futures

from concurrent.futures import ProcessPoolExecutor as Executor
#from concurrent.futures import ThreadPoolExecutor as Executor  # to use threads
with Executor() as executor:
    future1 = executor.submit(fun1, arg1, arg2, ...)
    future2 = executor.submit(fun2, arg1, arg2, ...)
    val1, val2 = future1.result(), future2.result()
    valsum = val1 + val2

concurrent.futures.Executor.submit安排要执行的函数,并返回concurrent.futures.Future个对象。

concurrent.futures.Future.result返回函数返回的返回值。

使用multiprocessing.pool

from multiprocessing.pool import Pool
#from multiprocessing.pool import ThreadPool as Pool  # to use threads
with multiprocessing.pool.Pool() as pool:
    result1 = pool.apply_async(fun1, (arg1, arg2, ...))
    result2 = pool.apply_async(fun2, (arg1, arg2, ...))
    val1, val2 = result1.get(), result2.get()
    valsum = val1 + val2

multiprocessing.pool.Pool.apply_async会返回AsyncResult个对象,并且 AsyncResult.get一旦完成,结果就会返回函数的返回值。