Python-线程处理-确保Timer()正确停止

时间:2018-10-26 16:22:31

标签: python multithreading python-multithreading

我想确保计时器在运行timer.cancel()后正确停止,但是我不确定是否正确执行了此操作。据我所知,首先您要通过运行cancel()来停止它,然后使用join()等到线程完全清理并终止为止。如果我在取消后运行join(),则join()之后的所有语句仅在线程完全终止后才执行。我能正确理解吗?

如果没有,我如何确保线程完全终止,并且我的下一行代码仅在线程终止后才能运行?

def f():
    timer = threading.Timer(5, f)

    if something_happens:
        timer.cancel()
        timer.join()

        do_something_after_timer_completely_stops()

1 个答案:

答案 0 :(得分:1)

您不必致电.join()。调用.cancel()足以停止计时器。但是,有一个警告:计时器只有在处于 waiting 阶段(在时间到期之前)才能停止。如果实际的代码已经在运行,则无法通过.cancel()停止它;它成为普通线程。

实现threading.Timer()类的方式使用等待的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!")