守护进程:设置一个线程是守护线程,就说明这不是一个很重要的线程,对于这样的线程,只要主线程运行结束,就会直接退出。而如果一个线程不是守护线程的话,即使主线程运行结束也不会退出,而是等待所有的非守护线程运行结束,再退出。。简单概念:守护线程主线挂了,子线程会挂掉。非守护线程,主线程挂掉,子线程还会继续继续。
1、守护线程&非守护线程举例:
A、守护进程:
import threading,time
def _demon():
for i in range(1,5):
print(i)
time.sleep(2)
t = threading.Thread(target=_demon)
t.setDaemon(True) #把线程设置为守护进程,要放在start前面执行
t.start()
print("end the process")
输出:
1
end the process
B、非守护进程:
import threading,time
def _demon():
for i in range(1,5):
print(i)
time.sleep(2)
t = threading.Thread(target=_demon)
t.setDaemon(False)
t.start()
print("end the process")
输出:
1
end the process
2
3
4
注:默认就是非守护进程,要设置进程为主进程,就要手动开启。