[英]Stop or Kill python Thread
I am having a problem trying to kill or stop a thread in python, since there aren't any official api I'm trying to find a way to stop a specified thread without killing others. 我有一个问题试图杀死或停止python中的线程,因为没有任何正式的api我试图找到一种方法来停止指定的线程而不杀死其他人。
Every time that i launch a thread i give it an ID 每次我启动一个线程我给它一个ID
t = threading.Thread(name=slug_ID, target=function)
Now on the main thread it is possible that the user asks to stop and delete the thread. 现在在主线程上,用户可能要求停止并删除该线程。 Since I'm launching different threads each one has his own slug_ID.
由于我正在启动不同的线程,因此每个线程都有自己的slug_ID。
for thread in threading.enumerate(): if (thread.getName()==slug_ID)): #thread.kill()
I'd like to kill the thread immediately, I've searched around and i found 2 possibilities: 我想立即杀死线程,我搜索了周围,我找到了两种可能性:
try: while True: thread_do_stuff() except Custom_signal: #exitThread
the problem is that i don't know how to crate and catch custom signals, any ideas on how can i resolve the problem? 问题是我不知道如何包装和捕捉自定义信号,任何关于如何解决问题的想法?
Python does not offer APIs for killing threads and reasons are well discussed here . Python没有提供用于杀死线程的API, 这里有很好的讨论。 Java, for example, used to expose specific methods for killing threads but it has been removed a long time ago.
例如,Java用于公开杀死线程的特定方法,但很久以前就被删除了。
In Python, signals are handled only in the main thread . 在Python中,信号仅在主线程中处理。 Therefore, your second approach would not work.
因此,你的第二种方法是行不通的。
If you need to stop abruptly a concurrent execution, the only safe way is to use processes instead of threads. 如果您需要突然停止并发执行,唯一安全的方法是使用进程而不是线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.