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
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]
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.