0

I have been trying to incorporate multithreading in my code which calculates the sum of the Fibonacci numbers whose index is given by a randomly generated number array. The array is of 10000 numbers. The problem is this code doesn't work for 10k numbers but sometimes works for 1000 numbers.

import random, threading

arr = []

def fibo(num, cache = {1:1, 2:1}):
    if num not in cache:
        cache[num] = fibo(num-1, cache) + fibo(num-2, cache)
    return cache[num]

def rand():
    global arr
    arr = [random.randrange(1, 21) for _ in range(10000)]


def func(arr):      
    fibo_arr = []
    fibo_arr  = [fibo(n) for n in arr]
    print(f'Sum: {sum(fibo_arr)}')

if __name__ == "__main__":
    x = threading.Thread(target=rand)
    x.start()  
    y = threading.Thread(target = func, args = (arr,))
    y.start()
    x.join() 
    y.join()

Why is the code only working for a specific range and that too with inconsistency? Is there a better way of doing this using synchronization?

  • Edit the question to explain "doesn't work". What happens (error messages?), what should happen? – Michael Butscher Jun 19 '20 at 01:58
  • Computing Fibonacci numbers is entirely compute bound (no IO at all). Adding `threading` will not speed anything up -- and might slow things down. Using `multiprocessing` might help, but not `threading`. – FMc Jun 19 '20 at 02:03
  • @MichaelButscher if my input is 1000, it will calculate the sum half the time, and if the input is even 2k, the sum gets returned as 0. – Piyush Agrawal Jun 19 '20 at 02:04
  • @FMc Thanks for the tip, I'll try multiprocessing for this but I still can't understand the inconsistency here. – Piyush Agrawal Jun 19 '20 at 02:06
  • Your use of `threading` is non-standard. Take a look at the pattern in this example: https://stackoverflow.com/questions/2846653/how-can-i-use-threading-in-python/2846697#2846697. Normally, you create some threads; push work-to-be-done into a thread-safe queue; and have the threads write results to another queue (not to a shared global variable with no synchronization controls). That answer also explains why Python threads won't help for your type of problem. Good luck! – FMc Jun 19 '20 at 02:11

0 Answers0