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

9 投票
2 回答
19565 浏览
提问于 2025-04-18 13:58

我刚开始学习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()

我想创建一个方法来停止这个线程。现在发生了什么呢?

2 个回答

-2
import threading
import time
class MultiThreading:

    def __init__(self):
        self.thread = None
        self.started = True
    def threaded_program(self):
        while self.started:
            print("running")
            # time.sleep(10)
    def run(self):
        self.thread = threading.Thread(target=self.threaded_program, args=())
        self.thread.start()
    def stop(self):
        self.started = False
        self.thread.join()

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

14

我觉得你可能忽略了文档中提到的“线程本身需要定期检查 stopped() 的状态”这一点。

你的线程应该这样运行:

while not self.stopped():
    # do stuff

而不是 while true。需要注意的是,它只会在循环的“开始”时退出,也就是检查条件的时候。如果循环里的内容执行得很久,可能会导致意外的延迟。

撰写回答