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

9

我刚接触Python编程。 我正在尝试制作一个带有可停止线程的GUI界面。 我借鉴了一些代码,来自 https://dev59.com/wXRC5IYBdhLWcg3wW_pk#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个回答

14

我认为你错过了文档中"The thread itself has to check regularly for the stopped() condition"这部分内容。

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

while not self.stopped():
    # do stuff

与其使用while true,更好的方法是使用其他控制结构。请注意,它仍然只会在循环的“开始”处退出,当它检查条件时。如果循环中的内容运行时间较长,则可能导致意外延迟。


更糟糕的是,有些人会这样做:while True: \n\t if not threadObject.stopped():。第一次看到有人为此浪费了一个完整的缩进级别,我感到非常震惊。 - Adrian

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

3
虽然原则上是正确的,但缺少解释。更糟糕的是,语义令人困惑:在执行run()方法之前,started已经被设置为True;在构造函数中,thread被设置为None,而不是在那里创建Thread()started应该被称为running(这一点可以从打印参数中看出)。 - NichtJens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接