在Python中强制退出正在运行的线程

时间:2018-11-08 03:49:00

标签: python multithreading python-2.7

我试图强制退出所有正在运行的线程,并在人们按Ctrl + C时进行清理。

我遵循了这个post,但是线程只有在睡眠时才退出。这是我的基类:

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()

尽管我已经调用了stop()方法,但是线程仍然尝试在退出前完成target()函数。如何强制退出target()函数?

这是复制的最少代码:

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

0 个答案:

没有答案