Python中的主线程是程序的起始线程,即程序启动时自动创建的第一个线程,它执行程序的主体逻辑。
守护线程则是在后台运行并依赖于主线程或非守护线程的存在。
【一】主线程死亡,子线程未死亡
主线程结束运行后不会马上结束,而是等待其他非守护子线程结束之后才会结束
如果主线程死亡就代表者主进程也死亡,随之而来的是所有子线程的死亡
from threading import Thread
import time
def work(name):
print(f'当前 {name} is beginning')
time.sleep(2)
print(f'当前 {name} is ending')
def main():
print(f' this is main process start ')
task = Thread(target=work, args=('dream',))
task.start()
print(f' this is main process end ')
if name == 'main':
main()
# this is main process start
# 当前 dream is beginning
# this is main process end
# 当前 dream is ending
【二】主线程死亡,子线程也死亡
from threading import Thread
import time
def work(name):
print(f'当前 {name} is beginning')
time.sleep(2)
print(f'当前 {name} is ending')
def main():
print(f' this is main process start ')
task = Thread(target=work, args=('dream',))
# 开启守护线程 , 主线程结束,子线程随之结束
task.daemon = True
task.start()
print(f' this is main process end ')
if name == 'main':
main()
# this is main process start
# 当前 dream is beginning
# this is main process end
标签:name,process,start,线程,print,main,守护
From: https://www.cnblogs.com/zenopan101861/p/18208227