Is there a way to kill a thread by name in pyhton?
For example, say that I create a thread like this
t = Thread(name='n', ...)
t.start()
Is it possible that later in my code to kill the thread with something like killThreadByName('n')
?
CodePudding user response:
There's no kill()
or stop()
in the high-level API, there's only join()
and is_alive()
.
name
A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. (source)
Judging by this docstring it'd be quite unwise to kill by a name unless you can ensure it being unique e.g. by having own wrapper around Thread.__init__()
with an assert
or so. Meaning, the wrapper for Thread.__init__()
will need to look somewhere to check such a name isn't already present. Then you can collect all of the running threads into some variable or better, a dict
:
threads = {}
threads["one"] = Thread(name="one", ...)
Alternatively, don't have it unique and treat the name
as a "class"/instance of a thread doing the same thing, if you have a use-case for it. Then the killing itself would be a loop over everything with the same name and the dict
would be something like this:
from collections import defaultdict
threads = defaultdict(list)
threads["one"].append(Thread(name="one", ...))
Otherwise, a Thread should be preferably stopped from within itself either by watching some outer variable or having a shared sharable/lockable resource which if signaled somehow to the thread would cause the thread to exit()
/return
or similar action leading to a clean stop that does not cause problems.
One of such resources can be threading.Event()
and watching for its state as mentioned here.
As to the actual thread killing, check this question and this answer.