While searching for a way to quickly kill a thread when using Python's out-of-the-box threading module, I came across this method: Use the Hidden _stop()
Function to Kill a Thread in Python
There is presumably a reason behind why the _stop()
function is protected rather than public. My assumption is that it's to make it difficult to terminate a thread unsafely, but I'm curious about whether there are any other reasons.
What are the downsides to calling _stop()
to kill a thread?
The code you linked to doesn't call the private ._stop()
function at all. Instead the constructor replaces it entirely with an Event
:
self._stop = threading.Event()
That appears senseless to me.
The actual private ._stop()
function does NOT stop a thread. There is nothing in threading.py
that can do so. Instead the private ._stop()
function is called internally to maintain Python-level module invariants after the C implementation has determined that a thread's life has (already) ended. There is no case in which it would make sense for user-level code to call it.
EDIT: by the way, in the current Python (>= 3.10), calling ._stop()
on a thread that's alive just dies at once with an AssertionError
, and that's its only effect. As I recall, in some older Python versions ._stop()
went on to corrupt some of threading.py
's internals (destroyed its knowledge of which threads were actually still alive). In no case, though, did it ever stop the thread.