Sep-02-2020, 01:21 AM
(This post was last modified: Sep-02-2020, 01:21 AM by deanhystad.)
from random import randint import time, threading def main(): times = [] for x in range(10): # Thought you said only 1 thread, not 10! targetVar = 0 start = time.time() t = threading.Thread(target = varUpdater, name = 'Thread1', args = (targetVar)) # args must be tuple t.start() end = time.time() # Not measuring time for thread, only thread launch time times.append(end - start) average = (sum(times)/ len(times)) print (average) def varUpdater(targetVar): var = randint(0, 100) time.sleep(0.01) if var > targetVar: return var # Why return value. No way to use it. else: return targetVar if __name__ == '__main__': main()As others have said, the main problem is args has to be a tuple and tuples with only 1 element need a trailing comma or the parenthesis are treated as blocking, not tuple initialization.
Your start and stop times are not measuring how long the tread takes. For example:
import threading import time start_time = time.time() def waiter(seconds): time.sleep(seconds) print ('waiter', time.time() - start_time) def main(): t = threading.Thread(target = waiter, name = 'Thread1', args = (5.0,)) t.start() print ('main', time.time() - start_time) main()
Output:main 0.0
>>> waiter 5.007939100265503
It takes nearly zero time to launch the tread, but the tread takes 5 seconds to complete.