停止运行无限循环的python线程 [英] Stopping a python thread running an Infinite Loop

查看:297
本文介绍了停止运行无限循环的python线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python编程的新手.我正在尝试制作具有可停止线程的GUI. 我从那里借了一些代码 https://stackoverflow.com/a/325528

I am new to python programming. I am trying to make a GUI with stoppable threads. I borrowed some code from 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()

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

I have function which creates a thread for another function in another class that runs an infinite loop.

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

我想创建一个方法来停止该线程. 这是怎么回事?

I want to create a method to stop this thread . What's happening here?

推荐答案

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

I think you missed the 'The thread itself has to check regularly for the stopped() condition' bit of that documentation.

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

Your thread needs to run like this:

while not self.stopped():
    # do stuff

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

rather than while true. Note that it is still only going to exit at the 'start' of a loop, when it checks the condition. If whatever is in that loop is long-running, that may cause unexpected delays.

这篇关于停止运行无限循环的python线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆