Is There Any Way to Abruptly Terminate a Thread?
Terminating a running thread without relying on flags or semaphores is generally not recommended in Python due to potential consequences. However, in certain scenarios, as described below, forcefully terminating a thread may be necessary.
Uncontrolled Thread Termination
Forcing a thread to stop abruptly can result in problems, such as:
Ideally, threads should be designed to gracefully exit upon receiving an exit request signal. This can be achieved using a shared flag that the thread checks periodically to determine if it should terminate.
Beispiel:
import threading class StoppableThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set()
Forced Thread Termination
In certain scenarios, such as when dealing with external libraries, it may be necessary to forcibly terminate a thread. This can be achieved using the following code, which allows raising an exception in a specific thread:
def _async_raise(tid, exctype): if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None) raise SystemError("PyThreadState_SetAsyncExc failed") class ThreadWithExc(threading.Thread): def _get_my_tid(self): if not self.is_alive(): raise threading.ThreadError("the thread is not active") if hasattr(self, "_thread_id"): return self._thread_id for tid, tobj in threading._active.items(): if tobj is self: self._thread_id = tid return tid raise AssertionError("could not determine the thread's id") def raise_exc(self, exctype): _async_raise( self._get_my_tid(), exctype )
Limitations of Forced Thread Termination
This method has limitations and may not work if the thread is executing code outside the Python interpreter. For reliable cleanup, it is recommended to have the thread catch a specific exception and perform appropriate actions.
The above is the detailed content of Can Threads in Python Be Abruptly Terminated, and If So, What Are the Limitations?. For more information, please follow other related articles on the PHP Chinese website!