Reputation: 979
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.
Upvotes: 0
Views: 228
Reputation: 179
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.
Upvotes: 1