问题
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