Python kill thread Python kill thread multithreading multithreading

Python kill thread


In general, raising asynchronous exceptions is difficult to handle properly. This is because, rather than having single, specific points of code where an exception may be generated--and therefore where exception handling needs to be tested--instead, an exception may be generated after any bytecode instruction. This makes it much harder to implement and fully test exception handling.

That said, it can be done--but, presently, not safely in Python. Raising an exception asynchronously in Python is dangerous, because you might raise it during an exception handler, which will raise another exception and prevent cleanup from occurring properly. See my answer at How to limit execution time of a function call in Python.

It's possible to signal some forms of sleep to cancel, but there's no general infrastructure for this in Python. You're much better off either avoiding the need to kill a thread, or moving the thread to a process, where you can send a signal to the whole process and exit cleanly.