守护线程

主进程死亡,子线程也死亡

"""守护线程"""
# 主进程死亡,子线程也死亡
# 导入模块
from threading import Thread
import time
def run_task():
    print(f"这是一个线程")
    time.sleep(3)
def main_thread():
    t=Thread(target=run_task)
    # 设置守护线程
    t.daemon=True
    # 开启线程
    t.start()
    print("主进程结束!!!")
if __name__ == '__main__':
    main_thread()
# 这是一个线程
# 主进程结束!!!

迷惑性例子

from threading import Thread
from multiprocessing import Process
import time


def foo():
    print(f' this is foo begin')
    time.sleep(1)
    print(f' this is foo end')


def func():
    print(f' this is func begin')
    time.sleep(3)
    print(f' this is func end')


def main():
    t1 = Thread(target=foo)
    t2 = Thread(target=func)
    t1.daemon = True
    t1.start()
    t2.start()

    print(f' this is main')


if __name__ == '__main__':
    main()
    
    #  this is foo begin
    #  this is func begin
    #  this is main
    #  this is foo end
    #  this is func end
  • 分析
    • t1 是守护线程,会随着主线程的死亡而死亡
    • 当多线程开启时,主线程运行,开启子线程
    • 再开启主线程
    • 主线程结束后会等待非守护子线程结束,所以需要等待3s,等待func结束运行
    • 所以执行顺序是 子线程1---子线程2---主线程---子线程1结束---子线程2结束
posted @   苏苏!!  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示