python线程奇怪的行为
我有一个计时器函数,我在另一个类似这样的函数中调用它python线程奇怪的行为,python,python-2.7,python-multithreading,Python,Python 2.7,Python Multithreading,我有一个计时器函数,我在另一个类似这样的函数中调用它 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 = r
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()
即使在输入“退出”命令后,函数也会打印“hello”
我无法找出您正在使用的代码有什么问题取消错误。在中,它表示:“与线程一样,通过调用其start()方法启动计时器。可以通过调用cancel()方法停止计时器(在其操作开始之前)。计时器在执行其操作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。”
在您的代码中,如果在计时线程已经开始执行(将在5秒钟内)之后尝试使用
cancel
,cancel
将一事无成。线程将永远保持在中,而循环在f
中,直到您给它某种强制中断。因此,在运行execute
后的前5秒内键入“exit”就可以了。它将在线程开始之前成功地停止计时器。但是当计时器停止并且线程开始执行f
中的代码后,将无法通过cancel
停止它,因为您使用的cancel
错误。在中,它表示:“与线程一样,通过调用其start()方法启动计时器。可以通过调用cancel()方法停止计时器(在其操作开始之前)。计时器在执行其操作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。”
在您的代码中,如果在计时线程已经开始执行(将在5秒钟内)之后尝试使用cancel
,cancel
将一事无成。线程将永远保持在中,而循环在f
中,直到您给它某种强制中断。因此,在运行execute
后的前5秒内键入“exit”就可以了。它将在线程开始之前成功地停止计时器。但是在计时器停止并且线程开始执行f
中的代码后,将无法通过cancel
类线程来停止它。timer-cancel()
停止计时器,并取消计时器操作的执行只有在计时器仍处于等待阶段时,此功能才会工作
一个非常简单的版本,你正在努力完成的可能是这样的
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()
要强制终止线程,请参见以下内容:
类线程。计时器-取消()
停止计时器,并取消计时器操作的执行只有在计时器仍处于等待阶段时,此功能才会工作
一个非常简单的版本,你正在努力完成的可能是这样的
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()
要强制终止线程,请参见以下内容: