如果python线程是守护线程,那么以为着这个线程是“不重要”的,“不重要”意味着如果他的父进程结束了但该守护线程没有运行完,守护进程就会被强制结束。如果线程是非守护线程,那么父进程只有等到守护线程运行完毕后才能结束。
在python中,线程通过threadName.setDaemon(True|False)
来设置是否为守护线程
代码实例:
父进程中调用两个线程,但父进程会瞬间运行完,观察两个线程的运行情况
import time
import threading
def write(content):
start_time = time.strftime("%Y/%m/%d-%H:%M:%S",time.localtime(time.time()))
string = "start writting %s at %s" % (content,start_time)
print(string)
time.sleep(5)
end_time =time.strftime("%Y/%m/%d-%H:%M:%S",time.localtime(time.time()))
string = "start writting %s at %s" %(content,end_time)
print(string)
def watch(content):
start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))
string = "start watching %s at %s" % (content, start_time)
print(string)
time.sleep(5)
end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))
string = "start watching %s at %s" % (content, end_time)
print(string)
threads = []
t1 = threading.Thread(target=write,args=("poem",))
t2 = threading.Thread(target=watch,args=("video",))
threads.append(t1)
threads.append(t2)
def for_test():
for thread in threads:
thread.setDaemon(False)
thread.start()
if __name__ == '__main__':
for_test()
输出结果
start writting poem at 2018/10/14-17:30:42
start watching video at 2018/10/14-17:30:42
start watching video at 2018/10/14-17:30:47
start writting poem at 2018/10/14-17:30:47
可以看到两个线程都成功运行结束
import time
import threading
def write(content):
start_time = time.strftime("%Y/%m/%d-%H:%M:%S",time.localtime(time.time()))
string = "start writting %s at %s" % (content,start_time)
print(string)
time.sleep(5)
end_time =time.strftime("%Y/%m/%d-%H:%M:%S",time.localtime(time.time()))
string = "start writting %s at %s" %(content,end_time)
print(string)
def watch(content):
start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))
string = "start watching %s at %s" % (content, start_time)
print(string)
time.sleep(5)
end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))
string = "start watching %s at %s" % (content, end_time)
print(string)
threads = []
t1 = threading.Thread(target=write,args=("poem",))
t2 = threading.Thread(target=watch,args=("video",))
threads.append(t1)
threads.append(t2)
def for_test():
for thread in threads:
thread.setDaemon(True)
thread.start()
if __name__ == '__main__':
# print("main start at %s" %(time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))))
for_test()
# print("main end at %s" %(time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))))
输出结果
start writting poem at 2018/10/14-17:32:47
start watching video at 2018/10/14-17:32:47
可以看到两个线程没有运行到结束,因父进程先运行结束了