1

I'm trying to implement a recursive Fibonacci series which returns the value at an index. It's a homework and needs to be done using multi-threading. This is what I've done so far. My question is how do I add the results from live_thread1 and live_thread2. The threads have to be created at every level in the recursion.

def Recursive(n):
    if n< 2:
        return n
    else:
        return Recursive(n- 1) + Recursive(n- 2)



def FibonacciThreads(n):
    if n< 2:
        return n
    else:
        thread1        = threading.Thread(target=FibonacciThreads,args=(n-1,))
        thread2        = threading.Thread(target=FibonacciThreads,args=(n-2,))
        thread1.start()
        thread2.start()
        thread1.join()
        thread2.join()
        return live_thread1+live_thread2
3
  • This is a very strange assignment. Why would you want to start a new thread does nothing but start a new thread (or two)? Commented Jul 2, 2011 at 18:12
  • You said this is homework, so you have to do it. But there is an overhead with creating a thread. This code will make lots of threads that do very little work. I don't think it would be a good idea to do this in real code. Commented Jul 2, 2011 at 18:15
  • This is crazy, exponential algorithm using threads? Oh my god.... Commented Jul 24, 2011 at 14:46

2 Answers 2

4

This is not possible, because you cannot retrieve the return-value of a function executed in another thread.

To implement the behavior you want, you have to make FibonacciThreads a callable object that stores the result as a member variable:

class FibonacciThreads(object):
    def __init__(self):
        self.result = None

    def __call__(self, n):
        # implement logic here as above 
        # instead of a return, store the result in self.result

You can use instances of this class like functions:

fib = FibonacciThreads() # create instance
fib(23) # calculate the number
print fib.result # retrieve the result

Note that, as I said in my comment, this is not a very smart use of threads. If this really is your assignment, it is a bad one.

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

Comments

1

You can pass a mutable object to the thread to use for storing the result. If you don't want to introduce a new data type, you can for example just use a single element list:

def fib(n, r):
    if n < 2:
        r[0] = n
    else:
        r1 = [None]
        r2 = [None]
        # Start fib() threads that use r1 and r2 for results.
        ...

        # Sum the results of the threads.
        r[0] = r1[0] + r2[0]

def FibonacciThreads(n):
    r = [None]
    fib(n, r)
    return r[0]

Comments

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.