主进程死亡,子线程也死亡
"""守护线程"""
# 主进程死亡,子线程也死亡
# 导入模块
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结束