Skip to main content
 首页 » 编程设计

Python线程无法取消

2024年10月24日1198°冷暖

我有一个 python 线程,它应该每秒显示一条消息,而脚本的其余部分继续运行。但是 timer.cancel 函数不起作用,因为即使在主循环终止后它仍然继续运行:

from threading import * 
import time 
import sys 
 
a = 0 
 
def x(): 
    while(True): 
        global a 
        print 
        print 'Beep', a 
        print 
        time.sleep(1)   # wait 1 second       
 
t = Timer(1.0, x)       # create thread 
t.start()               # start thread 
 
while True: 
    a = a + 1 
    print a 
    time.sleep(0.1) 
 
    if a > 30:     
        t.cancel() 
    if a > 50: 
        sys.exit() 

我做错了什么?

请您参考如下方法:

threading.Timer类有一个 cancel 方法,但它不会取消线程,它会阻止计时器实际触发。实际上,cancel 方法设置了一个threading.Event,而实际执行threading.Timer 的线程将在完成等待之后和之前检查该事件它实际上执行了回调。

这可能是一个 solution满足您的要求。

import threading 
import time 
import sys 
 
a = 0 
 
class TimerClass(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self) 
        self.event = threading.Event() 
 
    def run(self): 
        while not self.event.is_set(): 
            global a 
            print 
            print 'Beep', a 
            print 
            self.event.wait(1) 
 
    def stop(self): 
        self.event.set() 
 
t = TimerClass() 
t.start() 
 
while True: 
    a = a + 1 
    print a 
    time.sleep(0.1) 
 
    if a > 30:     
        t.stop() 
    if a > 50: 
        sys.exit()