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

Time:12-04

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?

CodePudding user response:

In your code, you are starting and joining the threads immediately after creating them, which means that only the first thread will be running for 3 seconds, and the others will be blocked until the first thread finishes. To fix this, you can move the start() and join() calls outside of the loop that creates the threads, like 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, ))

for i in range(0, threads_number):
    threads[i].start()

for i in range(0, threads_number):
    threads[i].join()

print("--- %s seconds ---" % (time.time() - start_time))

This way, all of the threads will start running at the same time and will run for 3 seconds each, so the total time taken should be 3 seconds.

  • Related