无法在被终止线程中终止循环

2024-04-29 01:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的脚本的要点是让一个名为stopper的函数在到达某个特定时间时向函数go\ to发送终止线程事件

当前,事件被触发,线程被认为是关闭的,并且终止。但gou to继续打印到命令行

我想不出如何正确地阻止它

import threading
import time

class Stop_Check(object):
    def __init__(self):
        self.thread1Stop = threading.Event()

    def stopper(self):
        t = 0
        while True:
            t = t + 1
            time.sleep(1.0)
            if t == 3 :
                self.thread1Stop.set()
                break
            else :
                print("I'm still going...")
                time.sleep(1.0)
                continue
        print("terminated")

    def go_to(self):
        while (not self.thread1Stop.is_set()):
            print("I am working!")
            time.sleep(1.0)

    def main(self):
        t1 = threading.Thread(target=self.go_to)
        t1.start()
        self.stopper()
        time.sleep(5.0)

if __name__ == '__main__' :
    sc = Stop_Check()
    sc.main()

Tags: to函数importselfgotimemaindef