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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With