1001

Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?

1
  • In particular, is there a way to generate an exception like KeyboardInterrupt within a thread? Jan 28, 2023 at 17:22

31 Answers 31

1
2
-3

The most simple way is this:

from threading import Thread
from time import sleep

def do_something():
    global thread_work
    while thread_work:
        print('doing something')
        sleep(5)
    print('Thread stopped')

thread_work = True
Thread(target=do_something).start()
sleep(5)
thread_work = False
1
  • its not stopping the thread, but passing over it
    – aleXela
    Jul 2, 2022 at 18:54
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.