THN
THN

Reputation: 3611

How to get the result of multiprocessing.Pool.apply_async

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.

Upvotes: 18

Views: 38727

Answers (2)

linusg
linusg

Reputation: 6429

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!

Upvotes: 30

Giannis Spiliopoulos
Giannis Spiliopoulos

Reputation: 2698

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.

Upvotes: 5

Related Questions