如何杀死这个threading.Timer?

Man*_*pez 2 python multithreading timer

我已经使用一个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)  
Run Code Online (Sandbox Code Playgroud)

当计数器等于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 
Run Code Online (Sandbox Code Playgroud)

hol*_*web 5

这里的问题可以通过更仔细地阅读文档来解决.计时器线程的cancel方法"......只有在计时器仍处于等待阶段时才会起作用."

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

更普遍的是,如果没有积极的合作,就没有办法杀死一个线程,因为几个 SO答案已经很好地总结了.

而不是使用cancel你应该设置某种标志,function以确定它是否应该终止其循环(因此终止整个线程).