守护线程
定义:守护线程,就是守护别的线程,守护谁呢,守护的是一个进程中的主线程
使用:
from threading import Thread
t = Thread()
t.setDaemon(True)
当主线程对出后,守护线程也就自动退出,再守护也没意义
守护线程与普通线程的区别在哪?
1)普通子线程与主线程之间没有谁等待谁结束的关系,竞争地位等同,一个进程中可能是主线程先结束,主线程结束后,整个进程也要等待子线程运行结束后才终止退出
2)但是如果存在守护线程的话,主线程一旦结束,守护线程也会随之终止,整个进程终止退出,守护线程处于被动地位。
join的作用?
join的作用主要是阻塞线程,直到当前被阻塞线程执行完毕,其他线程才能执行
通常,我们会阻塞子线程,子线程执行完毕后,再执行主线程
如果加了守护线程,同样,看看先阻塞的谁,只有阻塞的执行完毕,才能去执行未阻塞的线程
看个例子:
from threading import Thread
def big_dog(foods):
for i in range(3):
print('big dog eat {}, cnt={}'.format(foods, i+1))
def small_dog(foods):
for i in range(3):
print('small dog eat {}, cnt={}'.format(foods, i+1))
def people(foods):
for i in range(3):
print('human eat {}, cnt={}'.format(foods, i+1))
ths = []
t1 = Thread(target=big_dog, args=('meat',))
ths.append(t1)
t2 = Thread(target=small_dog, args=('milk',))
ths.append(t2)
t3 = Thread(target=people, args=('noodles',))
if __name__ == '__main__':
print("主线程开始运行")
for t in ths:
t.setDaemon(True)
t.start()
for t in ths:
t.join()
t3.start()
print("主线程运行完毕")
运行结果:
主线程开始运行
big dog eat meat, cnt=1
big dog eat meat, cnt=2
big dog eat meat, cnt=3
small dog eat milk, cnt=1
small dog eat milk, cnt=2
small dog eat milk, cnt=3
human eat noodles, cnt=1
human eat noodles, cnt=2
human eat noodles, cnt=3
主线程运行完毕
注释掉守护线程后的运行结果:
主线程开始运行
big dog eat meat, cnt=1
big dog eat meat, cnt=2
big dog eat meat, cnt=3
small dog eat milk, cnt=1
small dog eat milk, cnt=2
small dog eat milk, cnt=3
human eat noodles, cnt=1
主线程运行完毕
human eat noodles, cnt=2
human eat noodles, cnt=3
分析:
join起阻塞作用
setDaemon起守护作用,守护的是主线程,主线程退出,守护线程也退出