Search code examples
pythonmultithreadingthreadpoolpython-multiprocessingpython-multithreading

How to get count of threads from user and start Thread Python


I can start function with my own count of threads and it works:

start_time = time.time()
t1 = Thread(target=time.sleep, args=(3, ))
t2 = Thread(target=time.sleep, args=(3, ))
t1.start()
t2.start()
t1.join()
t2.join()
print("--- %s seconds ---" % (time.time() - start_time))

Output:

--- 3.00131893157959 seconds ---

but I want to input threads number from user, I tried to do this:

start_time = time.time()
threads_number = int(input('Input count of threads: ')) # User inputed 2

threads = list(range(0, 99999))

for i in range(0, threads_number):
    threads[i] = Thread(target=time.sleep, args=(3, ))
    threads[i].start()
    threads[i].join()
print("--- %s seconds ---" % (time.time() - start_time))

Output:

--- 7.817119359970093 seconds ---

How to make last output 3 seconds?


Solution

  • Before :

    t1.start()
    t2.start()
    t1.join()
    t2.join()
    

    Both thread start, then wait for both threads to finish (join).

    After :

    for i in range(0, threads_number):
        threads[i] = Thread(target=time.sleep, args=(3, ))
        threads[i].start()
        threads[i].join()
    

    First thread starts, then is waited to finish, then second thread starts, then is waited to finish, ...

    Solution : start all threads, then wait all threads.

    for i in range(0, threads_number):
        threads[i] = Thread(target=time.sleep, args=(3, ))
        threads[i].start()
    for i in range(0, threads_number):
        threads[i].join()
    

    Runs in ~3 seconds (if fast to write the number).