在 python 中按名称终止线程

Kill a thread by name in python

有没有办法在 pyhton 中通过名称杀死线程?

比如我创建一个这样的线程

t = Thread(name='n', ...)
t.start()

是否有可能稍后在我的代码中用 killThreadByName('n') 之类的东西终止线程?

high-levelAPI中没有kill()stop(),只有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)

从这个文档字符串来看,除非你能确保它是独一无二的,否则用一个名字来杀死它是非常不明智的,例如通过在 Thread.__init__() 周围使用 assert 左右的包装器。意思是,Thread.__init__() 的包装器需要在某处 查找以检查这样的名称是否已经存在。然后你可以将所有 运行 线程收集到某个变量或更好的变量中,一个 dict:

threads = {}
threads["one"] = Thread(name="one", ...)

或者,不要让它唯一,并将 name 视为一个“class”/执行相同操作的线程实例,如果您有一个 use-case它。然后杀戮本身将是一个循环遍历所有具有相同名称的东西并且 dict 将是这样的:

from collections import defaultdict
threads = defaultdict(list)
threads["one"].append(Thread(name="one", ...))

否则,最好通过观察一些外部变量或共享 sharable/lockable 资源从自身内部停止线程,如果以某种方式向线程发出信号,将导致线程 exit()/ return 或导致干净停止但不会导致问题的类似操作。

其中一个资源可以是 threading.Event() and watching for its state

至于真正的线程杀,check this question and this answer