简体   繁体   English

停止或杀死python线程

[英]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: 我想立即杀死线程,我搜索了周围,我找到了两种可能性:

  • Attribute/Flag : since the thread is cycling i can check if the flag has been marked and return it, unfortunately the thread is now cycling continuously so for example if the thread is sleeping at the moment won't die immediately but only once the part of the code where the the flag is checked the thread will die 属性/标志 :由于线程是循环的,我可以检查标志是否已被标记并返回它,不幸的是线程现在连续循环,例如,如果此时线程处于休眠状态,则不会立即死亡,而只是一次部分检查标志的代码,线程将死亡
  • Signals : when i launch the event on the main thread, the thread will catch the event and exit gracefully, unfortunately i should create custom signals in order to stop only the specific thread that i want to kill, i thought something like this: 信号 :当我在主线程上启动事件时,线程将捕获事件并优雅地退出,不幸的是我应该创建自定义信号以便仅停止我要杀死的特定线程,我想这样的事情:
 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM