python thread join方法_python线程join方法原理解析

这篇文章主要介绍了python线程join方法原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

几个事实

1 python 默认参数创建线程后,不管主线程是否执行完毕,都会等待子线程执行完毕才一起退出,有无join结果一样

2 如果创建线程,并且设置了daemon为true,即thread.setDaemon(True), 则主线程执行完毕后自动退出,不会等待子线程的执行结果。而且随着主线程退出,子线程也消亡。

3 join方法的作用是阻塞,等待子线程结束,join方法有一个参数是timeout,即如果主线程等待timeout,子线程还没有结束,则主线程强制结束子线程。

4 如果线程daemon属性为False, 则join里的timeout参数无效。主线程会一直等待子线程结束。

5 如果线程daemon属性为True, 则join里的timeout参数是有效的, 主线程会等待timeout时间后,结束子线程。此处有一个坑,即如果同时有N个子线程join(timeout),那么实际上主线程会等待的超时时间最长为 N * timeout, 因为每个子线程的超时开始时刻是上一个子线程超时结束的时刻。

测试代码

import threading,time

def func():

print "start thread time: ",time.strftime('%H:%M:%S')

time.sleep(3)

print "stop thread time: ",time.strftime('%H:%M:%S')

thread_list = []

for i in range(3):

t1 = threading.Thread(target=func)

#t1.setDaemon(True)

thread_list.append(t1)

for r in thread_list:

r.start()

for t in thread_list:

#t.join(1)

t.join()

print "stop main thread"

###子线程如果设置了t.join(timeout),则根据timeout的不同,结果会不同,前提是设置了setDaemon(True),否则join的timeout是没效的

#设置了setDaemon(True),但是没设置t.join()的运行结果:

#start thread time: 17:25:29

#start thread time: 17:25:29

#start thread time: 17:25:29

#stop main thread

#加了t1.setDaemon(True),并且设置了超时时间t.join(1)的运行结果:

#start thread time: 17:12:24

#start thread time: 17:12:24

#start thread time: 17:12:24

#stop main thread

#没加t1.setDaemon(True),并且设置了超时时间t.join(1)的运行结果,不过因为setDaemon的参数不是True所以就算设置了超时时间也没用:

#start thread time: 17:13:28

#start thread time: 17:13:28

#start thread time: 17:13:28

#stop main thread

#stop thread time: 17:13:31

#stop thread time: 17:13:31

#stop thread time: 17:13:31

#没加t1.setDaemon(True),但是设置了t.join(),没有超时时间的阻塞的运行结果:

#start thread time: 17:16:12

#start thread time: 17:16:12

#start thread time: 17:16:12

#stop thread time: 17:16:15

#stop thread time: 17:16:15

#stop thread time: 17:16:15

#stop main thread

#即没有设置setDaemon(True),也没有设置join()的运行结果:

#start thread time: 17:22:25

#start thread time: 17:22:25

#start thread time: 17:22:25

#stop main thread

#stop thread time: 17:22:28

#stop thread time: 17:22:28

#stop thread time: 17:22:28

总结:

如果想让子进程正常的运行结束(子进程中所有的内容都运行了),则如果设置join(timeout)的话,前提是设置setDaemon(True),且setDaemon的参数为True,且join(timeout)的超时时间必须大于子进程执行所需的时间,不然没等子进程运行结束就超时退出了或者直接设置join()不带超时时间,也不用设置setDaemon(True)了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值