Context: I've aleady read Is there any way to kill a Thread? and its answers, but here I'm focusing on a possible solution with a function (inside a wrapper?) that would automatically check a flag running
before actually running each line of code of the thread target function. Also I have already read Python, Stop a Thread but it does not solve the problem since the flag checking "granularity" is only once every while
loop, whereas I'd like it to be at each line of code.
With the following code (simplified for this question):
import threading, time
def character_loop():
while running:
print('character moving left')
time.sleep(1)
print('character moving middle')
time.sleep(1)
print('character moving right')
time.sleep(1)
running = True
threading.Thread(target=character_loop).start()
time.sleep(4.5)
running = False # how to stop *any* movement here?
time.sleep(10)
it is in fact doing two full loops, i.e. left/mid/right/left/mid/right, whereas I would like to stop any movement after 4.5 seconds.
How to have left/mid/right/left/<stop here!>
instead?
In other words, how to be able to stop a thread as soon as possible? (possibly after each line of code running in the thread target
function)
This works:
def character_loop():
while running:
print('character moving left')
if not running:
break
time.sleep(1)
if not running:
break
print('character moving middle')
if not running:
break
time.sleep(1)
if not running:
break
print('character moving right')
if not running:
break
time.sleep(1)
but having to add
if not running:
break
after each line of code in the main loop is really annoying.
I'm sure there's a general threading / scheduling solution for this: how to be able to stop a thread function as soon as possible, ideally after each line of code, and not only when the function comes back to while running:
?
PS: in my real code, it's not just print('character moving left')
but another function that takes a few milliseconds to seconds to complete depending on the action.