Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for threads to finish using join. Pretty basic

I have a pretty basic assignment, but am having an issue making my main thread wait for all the other threads I spawn to complete.

This code does not do much of anything, it is just meant as a threading exercise.

Here is my code:

import time
from threading import Thread

def printNumbers(lowEnd, highEnd):
    while(lowEnd <= highEnd):
        print(repr(lowEnd))
        lowEnd += 1


countTo = 100000

#Test using 1 thread.        
startSingleThread = time.clock()
printNumbers(0,countTo)
elapsedSingleThread = (time.clock() - startSingleThread)

#Test using 10 threads
numberOfThreads      = 10
countAmountPerThread = countTo/numberOfThreads

startTenThread = time.clock()
for i in range(numberOfThreads):
    threadLowEnd  = i*countAmountPerThread
    threadHighEnd = (i+1)*countAmountPerThread
    t = Thread(target=printNumbers, args=(threadLowEnd,threadHighEnd,))
    t.start()

#Join all existing threads to main thread.
for thread in threading.enumerate():
    if thread is not threading.currentThread():
        thread.join()

elapsedTenThread = (time.clock() - startTenThread)

print("Time for 1 thread: " + repr(elapsedSingleThread))
print("time for 10 threads: " + repr(elapsedTenThread))
like image 231
PFranchise Avatar asked Aug 13 '26 18:08

PFranchise


1 Answers

You can’t see the stderr because you’re printing so much to stdout, but you have this error:

Traceback (most recent call last):
  File "test.py", line 29, in <module>
    for thread in threading.enumerate():
NameError: name 'threading' is not defined

If I add import threading to the top, I get this output:

Time for 1 thread: 1.0224820000000001
time for 10 threads: 1.421281

…which might be what you were expecting to see, since it happens after all of the numbers are printed.

like image 94
Josh Lee Avatar answered Aug 16 '26 08:08

Josh Lee