Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6370695
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T00:57:49+00:00 2026-05-25T00:57:49+00:00

How do I parallelize a recursive function in Python? My function looks like this:

  • 0

How do I parallelize a recursive function in Python?

My function looks like this:

def f(x, depth):
    if x==0:
        return ...
    else :
        return [x] + map(lambda x:f(x, depth-1), list_of_values(x))

def list_of_values(x):
    # Heavy compute, pure function

When trying to parallelize it with multiprocessing.Pool.map, Windows opens an infinite number of processes and hangs.

What’s a good (preferably simple) way to parallelize it (for a single multicore machine)?

Here is the code that hangs:

from multiprocessing import Pool
pool = pool(processes=4)
def f(x, depth):
    if x==0:
        return ...
    else :
        return [x] + pool.map(lambda x:f(x, depth-1), list_of_values(x))

def list_of_values(x):
    # Heavy compute, pure function
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T00:57:50+00:00Added an answer on May 25, 2026 at 12:57 am

    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 the list. That is because it’s not clear to me from your example what the return type of f() would be, and using an integer makes the code simple to understand.

    This is complex because there are two different things happening in parallel:

    1. the calculation of the expensive function in the pool
    2. the recursive expansion of f()

    I am very careful to only use the pool to calculate the expensive function. In that way we don’t get an "explosion" of processes, but because this is asynchronous we need to postpone a lot of work for the callback that the worker calls once the expensive function is done.

    More than that, we need to use a countdown latch so that we know when all the separate sub-calls to f() are complete.

    There may be a simpler way (I am pretty sure there is, but I need to do other things), but perhaps 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) # no list, return 0
        else:
            n = x # need to know size of result beforehand
            latch = Latch(n) # wait for n entires to be calculated
            result = RawArray('i', n+1) # where we will assemble the map
            def delayed_map(values):
                '''This is the callback for the pool async process - it runs
                   in a separate thread within this process once the
                   expensive list has been calculated and orchestrates the
                   mapping of f over the result.'''
                result[0] = x # first value in list is x
                for (v, i) in enumerate(values):
                    def callback(fx, i=i):
                        '''This is the callback passed to f() and is called when
                           the function completes.  If it is the last of all the
                           calls in the map then it calls on_complete() (ie another
                           instance of this function) for the calling f().'''
                        result[i+1] = fx
                        if latch.decrement(): # have completed list
                            # at this point result contains [x]+map(f, ...)
                            on_complete(sum(result)) # so return sum
                    async_f(v, callback)
            # Ask worker to generate list then call delayed_map
            pool.apply_async(list_of_values, [x], callback=delayed_map)
    
    
    def run():
        '''Tie into the same mechanism as above, for the final value.'''
        result = Value('i')
        latch = Latch(1)
        def final_callback(value):
            result.value = value
            latch.decrement()
        async_f(6, final_callback)
        latch.join() # wait for everything to complete
        return result.value
    
    
    print(run())
    

    PS: I am using Python 3.2 and the ugliness above is because we are delaying computation of the final results (going back up the tree) until later. It’s possible something like generators or futures could simplify things.

    Also, I suspect you need a cache to avoid needlessly recalculating the expensive function when called with the same argument as earlier.

    See also yaniv’s answer – which seems to be an alternative way to reverse the order of the evaluation by being explicit about depth.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to use MPI to parallelize a function that is being called multiple
In a member function, I can parallelize using the shared member variable int *x
You always hear that functional code is inherently easier to parallelize than non-functional code,
Everyone has this huge massively parallelized supercomputer on their desktop in the form of
How do I parallelize my F# program using SSE3 instruction set? Does the F#
Problem statement : How to parallelize inserts in SQL Server (2008) I am performing
I want to parallelize a C serial code in a 100 node distributed memory
I wanted to know whether there is a way to parallelize a for loop
I want to get the community's perspective on this. If I have a process
I actually have an answer to my question but it is not parallelized so

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.