如何从multiprocessing.Process获取函数返回值?

时间:2020-11-03 17:48:32

标签: python multiprocessing

我有两个功能,我想同时运行它们。所以,我尝试了:

from multiprocessing import Process

def func1():
    for i in range(0, 100000000):
        pass
    return 'abc'
    
def func2():
    for i in range(0, 100000000):
        pass
    return 'xyz'
    
if __name__=='__main__':
    p1 = Process(target=func1()).start()
    p2 = Process(target=func2()).start()

现在,如何获取例如func1()的返回值?
例如,我可以使用print(func1())来获取返回值,但它会再次执行该函数,并且再次花费很长时间才能执行func1()。我如何不使函数再次运行以获取结果?

2 个答案:

答案 0 :(得分:0)

您还可以使用concurrent.futures模块

import concurrent.futures
_pool = concurrent.futures.ThreadPoolExecutor()

def func1():
    for i in range(0, 100000000):
        pass
    return 'abc'
    
def func2():
    for i in range(0, 100000000):
        pass
    return 'xyz'
    
if __name__=='__main__':
    p1 = _pool.submit(func1)
    p2 = _pool.submit(func2)

    print(p1.result(), p2.result())

答案 1 :(得分:0)

以下是我在评论中建议的使用multiprocessing.Pool完成的方法。

import multiprocessing

def func1():
    for i in range(0, 100000000):
        pass
    return 'abc'

def func2():
    for i in range(0, 100000000):
        pass
    return 'xyz'

if __name__=='__main__':

    funcs = func1, func2

    with multiprocessing.Pool() as pool:
        results = [pool.apply_async(func) for func in funcs]
        pool.close()
        pool.join()

    results = [result.get() for result in results]
    print(f'{results}')  # -> ['abc', 'xyz']