我有两个并行运行的函数,每个函数都返回一个值。我需要等待两个函数完成,然后处理它们的返回。我怎么能在python中实现这一点。假设
def fun1():
#do some calculation#
return val1
def fun2():
#do some calculation#
return val2
我希望fun1和fun2并行运行,然后需要计算
valsum = val1+val2
答案 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
返回函数返回的返回值。
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
一旦完成,结果就会返回函数的返回值。