2

I have a function which recursively calls itself. Here is an example:

def f(a,b=0):
    if b < 5:
        for i in range(10):
            a += f(a+i,b+1)
    return a+b

print f(3)

Now I want to run 10 function calls inside the function each one in a separate thread simultaneously but get the return from all in one variable together.

Could someone lead me into the right direction?

1 Answer 1

4

Try thinking more precisely about how you want the multithreading to work.

The way you asked the question suggests that you want to spawn 10 threads for each recursive function call. This means that after a single level of recursion, you'll have 100 threads, after 2 levels, you'll have 1000 threads, and so on. This is probably not what you want unless you're trying to freeze up your OS.

Two alternatives include:

  1. only spawn threads on the first call, but not on recursive calls, or
  2. create a thread pool and use a work queue.

Another approach would be to think about the math that's being done by the function and analytically simplify it to avoid the looping and/or recursion.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, Thanks for your reply. I would like to go with 1. but my problem is, that I don't know how to save the result of the return of all ten threads in one variable after they are finished calculating (currently my programm needs about 20 seconds without multithreading, but uses only 5% CPU, so I figured out I should use multithreading. Is this the right way?).
Multithreading can help. Note that in cpython, single-process multithreading doesn't improve performance because of the global interpreter lock (GIL), but the multiprocessing module can assist. You could add an extra named argument parallelize=True, and when you make the recursive calls, use parallelize=False. That said, the function given looks like it can be simplified to avoid or reduce the recursion. I wouldn't be surprised if it could be rewritten as a closed-form expression.
Should I avoid recursion? I think I could rewrite my code without recursion, but that would need at least 3 times as many lines of code as I have now. Is it good programming style to write recursive functions? For now I will try your suggestion with the extra argument.
I suspect it can be rewritten without recursion or looping by writing out the function as a mathematical expression on paper and finding an analytic solution. If that's not possible, a loop is likely faster, but may not be worth the code bloat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.