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))
You can’t see the stderr because you’re printing so much to stdout, but you have this error:
If I add
import threadingto the top, I get this output:…which might be what you were expecting to see, since it happens after all of the numbers are printed.