ok, sorry for the problems with this.
I'm going to answer a slightly different question, where f() returns the sum of the values in a list. this is because it is not clear to me from your example what the return type is f() , and using the whole code makes the code understandable.
this is difficult because two different things happen in parallel:
- calculating an expensive function in a pool
- recursive decomposition
f()
I am very careful to use the pool to calculate an expensive function. Thus, we do not get an “explosion” of processes. but since it is asynchronous, we need to defer most of the work for the callback that the worker calls when an expensive function is executed.
furthermore, we need to use the countdown latch so that we know when all of the individual sub-titles f() complete.
there may be a simpler way (I'm sure there are, but I need to do other things), but maybe this gives you an idea of what is possible:
from multiprocessing import Pool, Value, RawArray, RLock from time import sleep class Latch: '''A countdown latch that lets us wait for a job of "n" parts''' def __init__(self, n): self.__counter = Value('i', n) self.__lock = RLock() def decrement(self): with self.__lock: self.__counter.value -= 1 print('dec', self.read()) return self.read() == 0 def read(self): with self.__lock: return self.__counter.value def join(self): while self.read(): sleep(1) def list_of_values(x): '''An expensive function''' print(x, ': thinking...') sleep(1) print(x, ': thought') return list(range(x)) pool = Pool() def async_f(x, on_complete=None): '''Return the sum of the values in the expensive list''' if x == 0: on_complete(0)
ps I am using python3.2, and the ugliness above is that we delay the calculation of the final results (returning to the tree) until a later time. perhaps something like generators or futures could make things easier.
In addition, I suspect that you need a cache to avoid unnecessarily recounting an expensive function when called with the same argument as before.
see also yaniv answer - parallel recursive function in python? - This is, apparently, an alternative way to change the order of assessment, indicating the depth.