Tommy
Tommy

Reputation: 13672

Python; best practices for killing other threads

I want to know: what is the best practice for killing threads started by a main Python application in the case the main application receives a SIGINT?

I am doing the following thing, but I HIGHLY suspect that because needing to kill other started threads is such a common problem, that probably there is a better way to do it:

class Handler(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.keep_go = True

    def run(self):
        while self.keep_go:
            #do something

    def stop(self): #seems like i shouldn't have to do this myself
        self.keep_go = False
try:
    h = Handler()
    h.start()
    while True:   #ENTER SOME OTHER LOOP HERE
        #do something else
except KeyboardInterrupt: #seems like i shouldn't have to do this myself
    pass
finally:
    h.stop()

The following post is related, but it is not clear to me what the actual recommended practice is, because the answers are more of a "here's some possibly hackish way you can do this". Also, I do not need to kill somethng "abruptly"; I am ok with doing it "the right way": Is there any way to kill a Thread in Python?

Edit: I guess one minor flaw with my approach is that it does not kill the current processing in the while loop. It does not receive a "kill event" that "rolls" back this loop as a transaction, nor does it halt the remainder of the loop.

Upvotes: 0

Views: 241

Answers (1)

Kevin
Kevin

Reputation: 76234

I usually just set each thread's daemon attribute to True. That way, when the main thread terminates, so does everything else.

The documentation has a little more to say on the matter:

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

Upvotes: 2

Related Questions