2
import time
from threading import Timer
from random import randint
print("Every wrong answer is a 3s delay; you have 30s")
end = False
def lose():
    print(end)
    print("Time up!")
    time.sleep(1)
    print("Score is",pts,", with",wrong,"wrong answers.")
    time.sleep(1)
    input("enter to quit")
    quit()
timer = Timer(10,lose)
timer.start()
pts = 0
wrong = 0
while end == False:
    a = randint(5,50)
    b = randint(5,50)
    print(a,"+",b)
    ans = input()
    if ans.isnumeric():
        ans = int(ans)
    if ans == a+b:
        print("correct")
        pts = pts+1
    else:
        print("wrong,",a+b)
        wrong = wrong+1
        print("delay")
        time.sleep(3)
        print("delay end")
    print("")

When the timer finishes, the loop overlaps the 'lose' function, and it messes up on the line like this:

Time up!

45 + 10
55
Score iscorrect 
3 
, with29  0+  wrong answers.37


enter to quitwrong,p
 66
delay

How do I fix this issue?
Sorry if this question has already been answered, but I want to know.

Me_Moo0
  • 21
  • 6
  • looks like the GIL isn't working properly on that one. Surprising. – Jean-François Fabre Jan 09 '18 at 20:32
  • Don't you remember — threads are run sumultaneously, and with varying speed, and all this timing is unpredictable (depends on many factors). Can you avoid using threads? Can you go for asynchronous functions perhaps? – spacediver Jan 09 '18 at 20:32
  • Yeah, I think I could do that instead, so the while loop will repeat until start time is 30 less than current time, then 'lose' will play – Me_Moo0 Jan 09 '18 at 20:35

1 Answers1

2

Ideally, you should probably avoid using threads altogether, as mentioned in the comments.

However, if you are going to use threads, consider using a mutex to ensure that multiple threads are not trying to write to stdout at the same time.

For example:

# setup at the beginning:
from threading import Thread, Lock
mutex = Lock()

# surrounding each print statement:
mutex.acquire()
try:
    print('text')
finally:
    mutex.release()
Flight Odyssey
  • 2,267
  • 18
  • 25
  • I'd probably use [`with mutex:`](https://docs.python.org/3/library/threading.html#using-locks-conditions-and-semaphores-in-the-with-statement), but yeah. – Fred Larson Jan 09 '18 at 20:55