Python - 线程 - 确保 Timer() 正确停止
Python - Threading - Make sure that Timer() stops correctly
我想确保我的计时器在 运行 宁 timer.cancel()
之后正确停止,但我不确定我是否正确地这样做了。据我所知,首先你通过 运行ning cancel()
停止它,然后使用 join()
等到线程完全清理并终止。如果我在运行join()
取消后,join()
之后的任何语句只有在线程完全终止后才会执行。我理解正确吗?
如果不是,我如何确保我的线程完全终止,并且我的下一行代码将 运行 仅在线程终止后才执行?
def f():
timer = threading.Timer(5, f)
if something_happens:
timer.cancel()
timer.join()
do_something_after_timer_completely_stops()
您不必致电 .join()
。调用 .cancel()
足以停止计时器。但是,有一点需要注意:计时器只有在 waiting 阶段(在时间到期之前)才能停止。如果实际代码已经是 运行,则无法再被 .cancel()
停止;它成为一个普通的线程。
threading.Timer()
class 的实现方式使用等待的 threading.Event
实例,以允许取消计时器,但是如果计时器用完,则仅设置事件功能完成后。所以你不能用它来可靠地检测线程是否已经启动。如果您想收到通知,我建议您创建自己的事件对象。
示例:您正在创建一个计时器来调用 f
:
timer = threading.Timer(5, f)
相反,在调用 f
之前创建一个新事件和一个函数来设置它,并安排计时器调用您创建的新函数。
f_called = threading.Event()
def calls_f(*args, **kwds):
"""function that calls f after setting the event f_called"""
f_called.set()
return f(*args, **kwds)
timer = threading.Timer(5, calls_f)
然后您可以使用该事件来检查 f
是否已被调用:
if f_called.is_set():
print("Too bad, thread is already running, can't cancel the timer!")
我想确保我的计时器在 运行 宁 timer.cancel()
之后正确停止,但我不确定我是否正确地这样做了。据我所知,首先你通过 运行ning cancel()
停止它,然后使用 join()
等到线程完全清理并终止。如果我在运行join()
取消后,join()
之后的任何语句只有在线程完全终止后才会执行。我理解正确吗?
如果不是,我如何确保我的线程完全终止,并且我的下一行代码将 运行 仅在线程终止后才执行?
def f():
timer = threading.Timer(5, f)
if something_happens:
timer.cancel()
timer.join()
do_something_after_timer_completely_stops()
您不必致电 .join()
。调用 .cancel()
足以停止计时器。但是,有一点需要注意:计时器只有在 waiting 阶段(在时间到期之前)才能停止。如果实际代码已经是 运行,则无法再被 .cancel()
停止;它成为一个普通的线程。
threading.Timer()
class 的实现方式使用等待的 threading.Event
实例,以允许取消计时器,但是如果计时器用完,则仅设置事件功能完成后。所以你不能用它来可靠地检测线程是否已经启动。如果您想收到通知,我建议您创建自己的事件对象。
示例:您正在创建一个计时器来调用 f
:
timer = threading.Timer(5, f)
相反,在调用 f
之前创建一个新事件和一个函数来设置它,并安排计时器调用您创建的新函数。
f_called = threading.Event()
def calls_f(*args, **kwds):
"""function that calls f after setting the event f_called"""
f_called.set()
return f(*args, **kwds)
timer = threading.Timer(5, calls_f)
然后您可以使用该事件来检查 f
是否已被调用:
if f_called.is_set():
print("Too bad, thread is already running, can't cancel the timer!")