Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading