【问题标题】:How to kill this threading.Timer?如何杀死这个threading.Timer?
【发布时间】:2016-06-01 10:14:40
【问题描述】:

我使用Timer 对象启动了一个线程。现在,我想停止这个线程,但我不能。我用过cancel(),但它不起作用。我不知道为什么。

import threading
import time
import sys as system
def Nop():
    print("do nothing")
    return 0
def function():
    try:
        while True:
            print("hello world ")
            time.sleep(2)
    except KeyboardInterrupt:
            print( "Good job!! exception catched") 
t = threading.Timer(10, function)
t.start()
print(t.getName)
counter = 0
while True:
    try:
        time.sleep(1) 
        Nop()
        counter = counter +1
        print(counter)
        if counter == 20:
            print(t.getName)
            t.cancel()
            counter = 0
            break
        if t.is_alive() == False:
            print("The Timer thread is dead...")
    except KeyboardInterrupt:
        print("End of program")
        t.cancel()
        system.exit(0)
    except:
        print("something wrong happens...")
if t.is_alive() == True:
    print("timer is alive...")
    print(t.getName)
    t.cancel()
print("final")
system.exit(0)  

当 counter 等于 20 时线程应该停止,但它仍然活着。当我退出 while 循环时,还有另一个检查。 Timer 是活动的,是同一个线程,我尝试取消,但它不起作用。

有什么想法吗?

do nothing
17
hello world 
do nothing
18
do nothing
19
hello world do nothing

20
<bound method _Timer.getName of <_Timer(Thread-6, started daemon 9916)>>
timer is alive...
<bound method _Timer.getName of <_Timer(Thread-6, started daemon 9916)>>
final
To exit: use 'exit', 'quit', or Ctrl-D.
An exception has occurred, use %tb to see the full traceback.

SystemExit: 0

hello world 
hello world 
hello world 
hello world 

【问题讨论】:

    标签: python multithreading timer


    【解决方案1】:

    这里的问题可以通过仔细阅读the documentation来解决。定时器线程的cancel 方法“...只有在定时器仍处于等待阶段时才会起作用。”

    当您调用t.cancel 时,计时器已触发,并且其相关函数正在执行,因此它不再“处于等待阶段”,即使该函数实际上大部分时间都在休眠 - 这并不意味着它处于等待阶段,当计时器触发时终止..

    更一般地说,如果没有线程的积极合作,就没有办法杀死线程,因为several SO answers 已经总结得很好。

    您应该设置某种标志,而不是使用cancelfunction 会查看它以确定它是否应该终止其循环(并因此终止整个线程)。

    【讨论】:

    • 是的,你完全正确。我在函数中设置了一个标志来停止循环,现在可以工作了。谢谢
    【解决方案2】:

    试试:

    del threadTimer
    

    我不知道这是否行得通,但在等待阶段应该使用cancel 方法。有关更多帮助,请参阅文档。您正在尝试在等待阶段后使用取消计时器。 如果del 语句不起作用,试试这个:

    threadTimer = None
    

    希望这能有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-24
      • 1970-01-01
      • 2013-02-20
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多