简体   繁体   中英

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.

Every time that i launch a thread i give it an 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.

 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 . Java, for example, used to expose specific methods for killing threads but it has been removed a long time ago.

In Python, signals are handled only in the main thread . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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