Yes it is possible to terminate a running thread but before terminating or killing thread you should think of the following cases:-
Thread holds a critical resource that must be closed properly.
When we create one thread it creates several threads that must be killed.
So for handling this problem, we have a very nice way exit_request flag so that at regular intervals each thread check if it is time for it to exit.
Let’s understand this with an example:-
import threading
class StoppableThread(threading.Thread):
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
In this above code, you should call stop()on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.