守护线程
如果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()
print("main over")
if __name__ == '__main__':
for_test()
运行结果:
可以看到主线程瞬间结束,但是等待到子线程均运行完毕之后程序才退出。
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 a t %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()))))
运行结果:
我们可以看到主线程结束之后整个程序即退出了。
更新时间: 2019 11 12