How to get the result of multiprocessing.Pool.apply_async

懵懂的女人 提交于 2021-02-18 10:45:07

问题


I want to get the result of the function run by Pool.apply_async in Python.

How to assign the result to a variable in the parent process? I tried to use callback but it seems complicated.


回答1:


The solution is very simple:

import multiprocessing

def func():
    return 2**3**4

p = multiprocessing.Pool()
result = p.apply_async(func).get()
print(result)

Since Pool.apply_async() returns an AsyncResult, you can simply get the result from the AsyncResult.get() method.

Hope this helps!




回答2:


Well an easy way would be to have a helper class like this:

class Result():
    def __init__(self):
        self.val = None

    def update_result(self, val):
        self.val = val

result = Result()

def f(x):
    return x*x

pool.apply_async(f, (10,), callback=result.update_result)

When the thread runs and calculates the result it will call your callback which will update the result.val.

In any case you need to check that the thread has finished.



来源:https://stackoverflow.com/questions/42843203/how-to-get-the-result-of-multiprocessing-pool-apply-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!