2013-09-01 95 views
0

我有我打电话它在另一个功能是这样蟒蛇线程怪异的行为

import time 
import threading 
def f(): 
    while(True): 
     print "hello" 
     time.sleep(5) 

def execute(): 
    t = threading.Timer(5,f) 
    t.start() 
    command = '' 
    while command != 'exit': 
     command = raw_input() 
     if command == 'exit': 
      t.cancel() 

即使输入“exit”命令后,该功能是打印“你好” 我不能定时器功能找出什么是错的代码

回答

3

类threading.Timer - 取消() - Doc-Link

停止计时,并取消计时器的动作的执行。 这只有在定时器仍处于等待阶段时才有效。

你试图完成的一个非常简单的版本可能看起来像这样。

import threading 

_f_got_killed = threading.Event() 

def f(): 
    while(True): 
     print "hello" 
     _f_got_killed.wait(5) 
     if _f_got_killed.is_set(): 
      break 

def execute(): 
    t = threading.Timer(5,f) 
    t.start() 
    command = '' 
    while command != 'exit': 
     command = raw_input() 
     if command == 'exit': 
      _f_got_killed.set() 
      t.cancel() 

execute() 

对于这有力地杀死一个线程看看:

Is there any way to kill a Thread in Python?

2

您正在使用cancel错误。在http://docs.python.org/2/library/threading.html中,它指出:“定时器和线程一样,通过调用它们的start()方法来启动。可以通过调用cancel()方法来停止定时器(它的动作开始之前)。执行其动作可能与用户指定的时间间隔不完全相同。“

在您的代码中,如果您在计时线程已经开始执行(它将在5秒内)之后尝试使用cancelcancel完成任何操作。线程将永远保留在while循环中,直到您给它某种强制中断为止。因此,在运行execute后的第一个5秒内输入“exit”即可。它会在线程开始之前成功停止计时器。但是当你的计时器停止并且你的线程开始执行f中的代码之后,将无法通过cancel来停止它。