2

I'm trying to run a problem using a single thread then running the same problem using multi threads to show the difference in the two times of the running execution, however, the running time appears to be the same, so I guess that is because the threads are not running simultaneously(parallel). So if anyone can please tell me how to run them simultaneously.

import threading, time

def fib(n):
    if n <= 1:
        return 1
    return fib(n - 1) + fib(n - 2)

def fib_caller(l):
    global list
    for i in range(10):
        x = fib(l[i])
        print(x)
        list[i] = x



if __name__ == '__main__':
    list = [1, 37, 1, 37, 1, 37, 1, 37, 1, 37]

    choice = input(
        "Please choose whether to :\nSingle-threaded process : Enter s\nor\nMulti-threaded 
process  : Enter m\n")

    begin = time.time()

    if choice == 's' or 'S':
        t = threading.Thread(name="Single thread", target=fib_caller, args=(list, ))
        t.start()
        t.join()
    elif choice == 'm' or 'M':
        t1 = threading.Thread(name="Single thread", target=fib_caller, args=(list[0:2]))
        t1.start()
        t1.join()
        t2 = threading.Thread(name="Single thread", target=fib_caller, args=(list[2:4]))
        t2.start()
        t2.join()
        t3 = threading.Thread(name="Single thread", target=fib_caller, args=(list[4:6]))
        t3.start()
        t3.join()
        t4 = threading.Thread(name="Single thread", target=fib_caller, args=(list[6:8]))
        t4.start()
        t4.join()
        t5 = threading.Thread(name="Single thread", target=fib_caller, args=(list[8:10]))
        t5.start()
        t5.join()
    else:
        print('Invalid Input.')

    print(list)

end = time.time()
total = end - begin
print("Total execution time: " + str(total))

1 Answer 1

6

This is direct from the threading library documentation.

"CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously."

1
  • 1
    So, you mean that there is nothing that I can do to run these threads simultaneously, and if I want to run the function multiple times simultaneously I should use multiprocessing instead right? Aug 17, 2021 at 23:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.