1
在下面的例子中,计时器将每5秒钟不停地打印hello world
,并且永不停止,我如何允许计时器线程作为计时器(打印'hello world'),但也不能阻止程序的进展?Python:如何在线程中避免'等待'来停止程序流?
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?
您好上面的代码被通过一个stackoveflow问题https://stackoverflow.com/a/9812806/157416 这似乎有一个高票。我知道代码创建一个循环,这是所需的结果,但通过线程我想要断开从主线程的循环。 OP正在要求如何实现这一点。我会看看你提供的链接。但你的回答只是描述我迄今已经知道的。谢谢 – Mohammad
而您错过了示例代码中存在的** start()**调用。所以从这个角度来看:简单地退后一步,考虑我的答案是否解决了你的问题,如果是的话,请考虑接受。或者让我知道你到那里丢失了什么。 – GhostCat
好的,我会调查开始()电话谢谢。 – Mohammad