停止运行无限循环的python线程


问题内容

我是python编程的新手。我正在尝试使用可停止线程创建GUI。我从https://stackoverflow.com/a/325528借了一些代码

class MyThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

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

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

我有一个函数,它为运行无限循环的另一个类中的另一个函数创建线程。

class MyClass :

    def clicked_practice(self):

        self.practicethread = MyThread(target=self.infinite_loop_method)
        self.practicethread.start()

    def infinite_loop_method()
        while True :
            // Do something


    #This doesn't seem to work and I am still stuck in the loop

    def infinite_stop(self)
        if self.practicethread.isAlive():
        self.practicethread.stop()

我想创建一个方法来停止该线程。这里发生了什么事?


问题答案:

我认为您错过了该文档的 “线程本身必须定期检查stopped()条件” 位。

您的线程需要像这样运行:

while not self.stopped():
    # do stuff

而不是while true。请注意,当它检查条件时,它仍只会在循环的“开始”处退出。如果该循环中的任何内容长时间运行,则可能会导致意外的延迟。