Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
Python – Is There Any Way to Kill a Thread
killmultithreadingpythonpython-multithreadingterminate
killmultithreadingpythonpython-multithreadingterminate
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
Best Answer
It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:
The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.
For example:
In this code, you should call
stop()
on the thread when you want it to exit, and wait for the thread to exit properly usingjoin()
. The thread should check the stop flag at regular intervals.There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.
The following code allows (with some restrictions) to raise an Exception in a Python thread:
(Based on Killable Threads by Tomer Filiba. The quote about the return value of
PyThreadState_SetAsyncExc
appears to be from an old version of Python.)As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.
A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.