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__':
    # 创建一个线程给函数add
    thread1=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 = daemon
        else:
            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 threading
    module, 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类变量,后续创建的线程实例都继承该状态,即默认都为守护线程。

还需钻研

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值