VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • python多线程中:如何关闭线程?

使用 threading.Event 对象关闭子线程

Event 机制工作原理:
Event 是线程间通信的一种方式。其作用相当于1个全局flag,主线程通过控制 event 对象状态,来协调子线程步调。

使用方式
主线程创建 event 对象,并将其做为参数传给子线程
主线程可以用set()方法将event 对象置为true, 用clear()方法将其置为false。
子线程循环体内,检查 event 对象的值,如果为 True, 则退出循环。
子线程,可使用 event.wait() 将阻塞当前子进程,直至event 对象被置为true.
event 类的常用方法
set() 设置 True
clear() 设置 False,
wait() 使进程等待,直到flag被改为true.
is_set() 查询 event 对象,如被设置为真,则返回True, 否则返回False.

class StartDecisionTread(threading.Thread):
    def __init__(self, ins):
        super(StartDecisionTread, self).__init__()
        self.ins = ins
        self.stop_event = threading.Event()

    def run(self):
        while not self.stop_event.is_set():
            print(1)
            model_file_path = rf'1.db'
            if not os.path.exists(model_file_path): 
                self.stop_event.set()


thread1 = StartDecisionTread(1)
thread1.start()

子线程执行其任务循环,它每次循环都会检查event对象,该对象保持 false,就不会触发线程停止。

当主线程调用event对象的 set() 方法后,在子线程循环体内,调用event对象is_set()方法,发现event 对象为True后, 立即退出任务循环,结束运行。

来源:https://www.cnblogs.com/Pythonmiss/p/18070929


相关教程