I understand this is an extensively covered topic, so I will play off of the answers already available.
I have a thread that has an infinite loop in its run()
method. I'm implementing something similar to this, where there is a stop()
function added to an extended threading.Thread
class.
Consider this thread structure:
class StoppableThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(LogicThread, self).__init__(*args, **kwargs)
self._stop_flag = threading.Event()
def run(self):
while True:
if self.stopped():
break;
# Program logic goes here
def stop(self):
self._stop_flag.set()
def stopped(self):
return self._stop_flag.isSet()
This seems to work as expected. The thread seems to start and stop, given that calling A.isAlive();
returns false
in the terminate catch
block.
But the program does not exit. It stops executing the threads (I placed print
statements inside the run methods, so I can tell the thread run()
method has been exited), but the program doesn't terminate. I also tried setting thread.daemon = True
, but to no avail. It seems to me like the fail safe should be sys.exit()
but that doesn't work either.
Consider the main method:
import sys
if __name__ == '__main__':
try:
logging.info('Starting!')
A = StoppableThread()
A.start()
while True:
time.sleep(100);
except KeyboardInterrupt:
logging.critical('Program terminating!')
A.stop()
A.join()
logging.critical('Program exited!')
sys.exit()
And advice you can give to help me fix this issue would be greatly appreciated. Thank you!