0

I would like to kill a thread in python upon certain events.

For example, I have a class within the class there is a neccessary function, for example this:

class exampleClass:
    def neccessary_function(self):
        try:
            do_something()
            return
        except:
            kill_this_thread()

I have multiple threads running simultaneously and I only want to kill that specific thread not all of them.

I can't return the function or anything like that, I need to either stop the thread doing anything or kill it. I currently have in the except section:

while True:
    time.sleep(300)

But I feel as though that is not the best way to do it.

GAP2002
  • 870
  • 4
  • 20
  • This question might already have an answer here: https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread – DaveIdito Nov 23 '20 at 18:01
  • Just to clarify - is the thread running in some kind of loop that you want to interrupt upon certain events? – DanDayne Nov 23 '20 at 18:03
  • The thread runs certain tasks if a certain event happens it will run the necessary function. If there's an exception in the necessary function I want to kill the thread @DanDayne – GAP2002 Nov 23 '20 at 18:06
  • What if you created a custom ThreadCancellationException and threw it after the necessary function is executed? – DanDayne Nov 23 '20 at 18:46
  • @DanDayne so to clarify, in the except loop I would raise that exception and that would end the thread? – GAP2002 Nov 23 '20 at 19:27
  • @GAP2002 while that is possible and would stop the thread, it can lead to problems as explained in my final answer – DanDayne Nov 24 '20 at 01:00

1 Answers1

1

It is generally considered unsafe to kill a thread - it could still be holding onto some resources and can lead to deadlocks.

You can look at ways to kill a thread, although as long as you want to be safe, your options are just to "ask the thread kindly to stop when it's ready".

I would suggest you take a look at multiprocessing or asyncio - both APIs provide a rather simple way to cancel an async operation.

DanDayne
  • 154
  • 6