Python:如何避免';等等';在停止程序流的线程中?

Python:如何避免';等等';在停止程序流的线程中?,python,multithreading,timer,wait,python-multithreading,Python,Multithreading,Timer,Wait,Python Multithreading,在下面的示例中,计时器将保持每5秒打印一次hello world,并且从不停止,我如何允许计时器线程作为计时器运行(打印“hello world”),但又不停止程序的进程 import threading class Timer_Class(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.event = threading.Event()

在下面的示例中,计时器将保持每5秒打印一次
hello world
,并且从不停止,我如何允许计时器线程作为计时器运行(打印“hello world”),但又不停止程序的进程

import threading
class Timer_Class(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.running = True
    def run(self, timer_wait, my_fun, print_text):
        while self.running:
            my_fun(print_text)
            self.event.wait(timer_wait)

    def stop(self):
        self.running = False




def print_something(text_to_print):
    print(text_to_print)


timr = Timer_Class()
timr.run(5, print_something, 'hello world')
timr.stop() # How can I get the program to execute this line?
首先:

while self.running:
您的代码包含一个循环,该循环将一直循环,直到循环条件
self.running
以某种方式更改为
False

如果您不想循环,我建议您删除代码中的循环部分

然后:您在线程对象上调用
start()
,而不是。因此,当前代码在主线程上执行所有操作。为了真正利用多个线程,您必须在某个时候调用
timr.start()


因此,这里真正的答案是:退一步,了解多线程如何在Python中工作(例如,看一看)。您似乎已经听到了一些概念,并开始尝试/出错。这是一个非常低效的策略。

您好,上面的代码被stackoveflow问题采用,该问题似乎有很高的投票率。我知道代码正在创建一个循环,这是期望的结果,但是通过线程,我尝试断开循环与主线程的连接。OP正在询问如何实现这一点。我会看看你提供的链接。但你的回答只是描述了我目前所知道的。谢谢,您错过了示例代码中的start()调用。所以从这个角度来看:简单地后退一步,考虑我的答案是否解决了你的问题,如果是这样,请考虑接受。或者让我知道你还缺少什么。好的,我将研究start()调用谢谢。start()似乎使线程并行运行,我可以问一下为什么直接调用run()不会有相同的结果吗?很简单:因为线程就是这样工作的。线程是允许您启动并行执行线程的抽象。这个抽象需要你启动这个线程,好让它启动。这就像在问“为什么我必须转动钥匙才能启动发动机——为什么仅仅坐在车里还不够好?”