python的守护线程设置
很简单的代码
import time
from threading import Thread
# 定义一个函数
def add(a,b):# 阻塞一秒钟,区别显示主线程和子线程for i in range(3):time.sleep(1)print(f'这是第{i}轮')
if __name__ == '__main__':# 创建一个线程给函数addthread1=Thread(group=None,target=add,args=(1,2))# 给子线程加入了线程守护Thread.daemon=True# 让线程开始执行thread1.start()# 主线程需要执行打印的内容print('这是主线程的内容')
在执行过程当中,没有给新建的子线程设定“守护”,因为Thread.daemon=True属于随手敲出来的,莫名其妙地完成了对该子线程的守护,试着摸索了下其中的逻辑:
1.在主线程中创建目标子线程thread1,因为没有指定daemon值,默认是None,python会通过current_thread()方法找到当前线程实例,并获取它的daemon值
if daemon is not None:if daemon and not _daemon_threads_allowed():raise RuntimeError('daemon threads are disabled in this (sub)interpreter')self._daemonic = daemonelse:self._daemonic = current_thread().daemon
2.current_thread()方法
def current_thread():"""Return the current Thread object, corresponding to the caller's thread of control.If the caller's thread of control was not created through the threadingmodule, a dummy thread object with limited functionality is returned."""try:return _active[get_ident()]except KeyError:return _DummyThread()
3._active通过get_ident()方法返回的实例对象的序号,在map中获得当前的线程实例对象
_active = {} # maps thread id to Thread object
通过上述逻辑,要创建的子线程获取到了当前线程,也就是它的父线程实例对象,而通过Thread.daemon=True改变了Thread类变量,后续创建的线程实例都继承该状态,即默认都为守护线程。
还需钻研