0

I'm trying to force quit all running threads and do clean up when people press Ctrl+C.

I followed this post, but threads only quit if they are sleeping. This is my base class:

class StoppableThread(threading.Thread):

    def __init__(self, timeout):
        threading.Thread.__init__(self)
        self._timeout = timeout
        self._stop = threading.Event()

    def run(self):
        while not self.stopped():
            self._stop.wait(timeout=self._timeout)  # instead of sleeping
            if self.stopped():
                break
            self.target()

    def cleanup(self):
        pass

    def target(self):
        pass

    def stop(self):
        self._stop.set()
        self.cleanup()

    def stopped(self):
        return self._stop.isSet()

Although I've called stop() method, thread still try to finish target() function before quitting. How can I force exiting from target() function?

This is minimal code to reproduce:

class TestThread(StoppableThread):
    def __init__(self):
        super(TestThread, self).__init__(2)  # sleep 2 seconds

    def target(self):
        print 'Begin `target` function'
        sleep(10)  # simulate long-running task
        print 'Finish `target` function'

    def cleanup(self):
        print 'Clean Up'


if __name__ == '__main__':
    t1 = TestThread()
    t1.start()
    print 'Thread 1 started'

    t1.stop()  # before run into `target`
    t1.join()  # quit immediately

    print '\n################\n'

    t2 = TestThread()
    t2.start()
    print 'Thread 2 started'
    sleep(3)

    t2.stop()  # after run into `target`
    t2.join()  # blocking until `target` finished
Viet Phan
  • 1,999
  • 3
  • 23
  • 40

0 Answers0