How to kill thread in python?
4195
09-Oct-2014
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
Anonymous User
09-Oct-2014It is generally a bad pattern to kill a thread abruptly, in Python and in any language. Think of the following cases:
· the thread is holding a critical resource that must be closed properly
· the thread has created several other threads that must be killed as well.
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 threads checks on regular interval to see if it is time for him to exit.
import threading
In this 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.
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:
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.