2017-09-27 49 views
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? 

回答

2

首先:

while self.running: 

你的代码包含一个循环,将不断循环,直到循环条件self.running莫名其妙改为False

如果你不想循环,我建议你删除循环部分在你的代码。

然后:你是而不是你的线程对象调用start()。所以你目前代码确实是一切的主线程。为了真正使用多个线程,您必须在某个时间呼叫timr.start()

所以real回答这里:退一步了解多线程如何在Python中工作(例如看看here)。看来你已经听到了一些概念并进行了试验/错误。这是一个非常低效的策略。

+0

您好上面的代码被通过一个stackoveflow问题https://stackoverflow.com/a/9812806/157416 这似乎有一个高票。我知道代码创建一个循环,这是所需的结果,但通过线程我想要断开从主线程的循环。 OP正在要求如何实现这一点。我会看看你提供的链接。但你的回答只是描述我迄今已经知道的。谢谢 – Mohammad

+0

而您错过了示例代码中存在的** start()**调用。所以从这个角度来看:简单地退后一步,考虑我的答案是否解决了你的问题,如果是的话,请考虑接受。或者让我知道你到那里丢失了什么。 – GhostCat

+0

好的,我会调查开始()电话谢谢。 – Mohammad

相关问题