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)了

猜你喜欢

转载自www.cnblogs.com/nyist-xsk/p/9350799.html