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

Ada*_* Xu 6 python multithreading

我是python编程的新手.我正在尝试使用可停止的线程创建GUI.我从/sf/answers/22786991/借用了一些代码

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()
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

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

aru*_*nte 6

我想你错过了'线程本身必须定期检查该文档的停止()条件.

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

while not self.stopped():
    # do stuff
Run Code Online (Sandbox Code Playgroud)

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