码迷,mamicode.com
首页 > 编程语言 > 详细

守护线程

时间:2017-11-25 20:06:19      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:设置   启动   code   mon   range   [46]   thread   art   结束   

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、

 

 

守护线程

标签:设置   启动   code   mon   range   [46]   thread   art   结束   

原文地址:http://www.cnblogs.com/wulafuer/p/7896158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!