![]() |
Inconsistent counting / timing with threading - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Inconsistent counting / timing with threading (/thread-35624.html) |
Inconsistent counting / timing with threading - rantwhy - Nov-24-2021 I have made a counter using threading I'm not sure why when the tick thread is flipping between 1 and 0 it is not consistent with its timing. Also with my incremental counter counting the changes of the other thread it changes the value in clumps. import threading import time countval = 0 def tick(): global countval while True: countval = 1 time.sleep(1) countval = 0 time.sleep(1) print ("clock value: " + str(countval)) def increment_value(): global countval plus = 0 flip = 1 while True: if countval == flip: plus = plus + 1 flip = 0 print ("count up value: " + str(plus)) if countval == 0: flip = 1 incr_thread = threading.Thread(target=increment_value) tick = threading.Thread(target=tick) incr_thread.start() tick.start()Here's the output I get what would cause it to be so inconsistent? I would expect it to output count up value then clock value and so on but it sometimes puts 2 count up values. Quote:count up value: 1 RE: Inconsistent counting / timing with threading - deanhystad - Nov-24-2021 I would expect something like this: import threading import time toggle = 0 def tick(): global toggle while True: time.sleep(1) toggle = 0 if toggle == 1 else 1 print ("toggle:", toggle) def increment_value(): last = toggle count = 0 while True: if last != toggle: last = 0 if last == 1 else 1 count += 1 print ("count:", count) incr_thread = threading.Thread(target=increment_value) tick = threading.Thread(target=tick) incr_thread.start() tick.start()As far as increment_value() is concerned, countval can change at any time. Your code behaves differently depending on where it is in increment_value() when countval changes. def increment_value(): global countval plus = 0 flip = 1 while True: if countval == flip: # If countval changes 1->0 here, flip == countval so plus is incremented plus = plus + 1 flip = 0 print ("count up value: " + str(plus)) if countval == 0: # If countval changes 1->0 here, flip is set to 1 and we don't count the tick flip = 1 |