2

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!

Community
  • 1
  • 1
James Taylor
  • 6,158
  • 8
  • 48
  • 74
  • Does execution actually reach the `if self.stopped()` check? It might get stuck in `# Program logic goes here` and never reach the termination check. – user2357112 Apr 27 '15 at 22:39
  • Thanks for the comment! For testing purposes the logic is just a `print()` statement. I know it reaches this check not only because the thread stops printing but also because `A.isAlive();` returns `false` in the `catch` block. – James Taylor Apr 27 '15 at 22:43
  • How do you determine whether the program has exited? And can you provide a minimal runnable version of your code that demonstrates the problem when you run it? – user2357112 Apr 27 '15 at 22:46
  • 1
    What platform/version of Python are you running? Running the program and then using Ctrl+C exits the program properly for me on a Linux machine running Python 2.7.6. – dano Apr 28 '15 at 01:12
  • After fixing some errors (missing import for `threading`, `time` and `logging`, wrong class name in *super()*) it works just fine for me in Python 3.4. – Nikratio Apr 28 '15 at 02:05

0 Answers0