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

停止运行无限循环的python线程,python,multithreading,Python,Multithreading,我是python编程新手。我正在尝试制作一个带有可停止线程的GUI。 我从你那里借了一些代码 我有一个函数,它为运行无限循环的另一个类中的另一个函数创建一个线程 class MyClass : def clicked_practice(self): self.practicethread = MyThread(target=self.infinite_loop_method) self.practicethread.start() def

我是python编程新手。我正在尝试制作一个带有可停止线程的GUI。 我从你那里借了一些代码

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

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
而不是
,而为true
。注意,当它检查条件时,它仍然只会在循环的“开始”退出。如果该循环中的任何内容是长时间运行的,则可能会导致意外的延迟

导入线程
导入时间
类多线程:
定义初始化(自):
self.thread=None
self.start=True
def螺纹螺纹_程序(自):
自启动时:
打印(“运行”)
#时间。睡眠(10)
def运行(自):
self.thread=threading.thread(目标=self.threaded_程序,args=())
self.thread.start()
def停止(自):
self.start=False
self.thread.join()

更糟糕的是,有些人这样做:
而True:\n\t如果不是threadObject.stopped():
。当我第一次看到有人为了这个而浪费了整个缩进级别时,我非常震惊。虽然原则上是正确的,但这缺少了一个解释。更糟糕的是,语义混乱:
started
设置为
True
,然后执行
run()
<在构造函数中将code>thread设置为
None
,而不是在那里创建的
thread()
started
应被称为
running
(这从print参数中可以明显看出)。
while not self.stopped():
    # do stuff