Python Forum
Help with learning threading please.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with learning threading please.
#4
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.
Reply


Messages In This Thread
RE: Help with learning threading please. - by deanhystad - Sep-02-2020, 01:21 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Concurrent futures threading running at same speed as non-threading billykid999 13 1,904 May-03-2023, 08:22 AM
Last Post: billykid999
  Tutorials on sockets, threading and multi-threading? muzikman 2 2,146 Oct-01-2021, 08:32 PM
Last Post: muzikman
  [split] Help with learning threading please. kalinuxman 1 1,844 Sep-02-2020, 04:40 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020