0

Is it possible to stop a Thread that is executing an infinite loop?

I have created a Thread with a function that executes a code that has an infinite loop, however when I try to stop the Thread the code keeps running, maybe it is not possible to stop a Thread with an infinite loop?

import threading
import time

script = """
while True:
    print("hi")
"""

def excute_script():
    exec(script)

script_thread = threading.Thread(target=excute_script)
script_thread.start()

time.sleep(2.0)

script_thread.join()
  • You need to stop the while-loop, not the thread. One way to do it is use a simple flag: `running = True; while running: print("hi")`, and then do `running = False` to break out of the loop. – ekhumoro Aug 20 '23 at 12:09

0 Answers0