python 守护线程是什么_python 守护线程

守护线程

如果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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值