In my program, I have a thread that continuosly listens to a UDP socket and if it gets any message, puts it in a queue.
Other threads basically do the main part of the program.
So when I want to terminate the program neatly. So I want a way to either kill the thread forcibly (but neatly) or to come out of recv()
of the socket at regular intervals so that I can check some state variables and quit if I need to.
CodePudding user response:
Forcefully killing threads is generally bad practice and should be avoided whenever possible.
According to the docs:
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.
Based on this information, I would recommend closing the thread using an Event. There is a really good example of this here: Is there any way to kill a Thread?
CodePudding user response:
This is what I regularly use:
import threading
class CustomThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(CustomThread, self).__init__(*args, **kwargs)
self._stopper = threading.Event()
def stop(self):
self._stopper.set()
def stopped(self):
return self._stopper.isSet()
def run(self):
while not self.stopped():
"""
The Code executed by your Thread comes here.
Keep in mind that you have to use recv() in a non-blocking manner
"""
if __name__ == "__main__":
t = CustomThread()
t.start()
# ...
t.stop()