守護線程
1、守護線程
當主線程退出時,守護線程就自動退出,無論守護線程是否已經執行完成。
import threading
import time
def worker(n):
print ("threading [%s] is begin!" % n)
time.sleep(2)
print ("threading [%s] is end!" % n)
start_time = time.time()
for i in range(50):
t = threading.Thread(target=worker,args = ("Thread-[%s]" % i,))
t.setDaemon(True)#將子線程設置為守護線程
t.start()
print ("all is done !")
cost_time = time.time() - start_time
print (cost_time)
執行結果:
threading [Thread-[0]] is begin!
threading [Thread-[1]] is begin!
threading [Thread-[2]] is begin!
threading [Thread-[3]] is begin!
threading [Thread-[4]] is begin!
threading [Thread-[5]] is begin!
threading [Thread-[6]] is begin!
threading [Thread-[7]] is begin!
threading [Thread-[8]] is begin!
threading [Thread-[9]] is begin!
threading [Thread-[10]] is begin!
threading [Thread-[11]] is begin!
threading [Thread-[12]] is begin!
threading [Thread-[13]] is begin!
threading [Thread-[14]] is begin!
threading [Thread-[15]] is begin!
threading [Thread-[16]] is begin!
threading [Thread-[17]] is begin!
threading [Thread-[18]] is begin!
threading [Thread-[19]] is begin!
threading [Thread-[20]] is begin!
threading [Thread-[21]] is begin!
threading [Thread-[22]] is begin!
threading [Thread-[23]] is begin!
threading [Thread-[24]] is begin!
threading [Thread-[25]] is begin!
threading [Thread-[26]] is begin!
threading [Thread-[27]] is begin!
threading [Thread-[28]] is begin!
threading [Thread-[29]] is begin!
threading [Thread-[30]] is begin!
threading [Thread-[31]] is begin!
threading [Thread-[32]] is begin!
threading [Thread-[33]] is begin!
threading [Thread-[34]] is begin!
threading [Thread-[35]] is begin!
threading [Thread-[36]] is begin!
threading [Thread-[37]] is begin!
threading [Thread-[38]] is begin!
threading [Thread-[39]] is begin!
threading [Thread-[40]] is begin!
threading [Thread-[41]] is begin!
threading [Thread-[42]] is begin!
threading [Thread-[43]] is begin!
threading [Thread-[44]] is begin!
threading [Thread-[45]] is begin!
threading [Thread-[46]] is begin!
threading [Thread-[47]] is begin!
threading [Thread-[48]] is begin!
threading [Thread-[49]] is begin!
all is done !
0.018001079559326172
Process finished with exit code 0
從結果中可以看到,主線程結束後,程序自動退出,子線程雖然啟動,但未執行完成。
2、
守護線程