在下面的示例中,计时器将每 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 中的工作原理(例如看看 here )。看来您已经听说过一些概念并进行尝试/错误。这是一个非常低效的策略。
关于Python:如何避免线程中的 'wait'停止程序流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46442302/