本文共 2292 字,大约阅读时间需要 7 分钟。
1 python 默认参数创建线程后,不管主线程是否执行完毕,都会等待子线程执行完毕才一起退出,有无join结果一样
例子如下:import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___',time.time())t = threading.Thread(target=say,args=('eve',))t.start()t.join()print('___主线程结束___',time.time())
import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___',time.time())t = threading.Thread(target=say,args=('eve',))t.start()#t.join()print('___主线程结束___',time.time())
2 如果创建线程,并且设置了daemon为true,即thread.setDaemon(True), 则主线程执行完毕后自动退出,不会等待子线程的执行结果。而且随着主线程退出,子线程也消亡。
例子如下:import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___')t = threading.Thread(target=say,args=('eve',))t.setDaemon(True)t.start()# t.join()print('___主线程结束___')
3 join方法的作用是阻塞,等待子线程结束,join方法有一个参数是timeout,即如果主线程等待timeout,子线程还没有结束,则主线程强制结束子线程。
例子如下:①.主线程超时时间小于子线程运行时间,主线程结束了,不管子线程是否结束都结束了import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___')t = threading.Thread(target=say,args=('eve',))t.setDaemon(True)t.start()t.join(2)print('___主线程结束___')
②.主线程超时时间大于子线程运行时间,主线程等待子线程结束候结束了
import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___')t = threading.Thread(target=say,args=('eve',))t.setDaemon(True)t.start()t.join(4)print('___主线程结束___')
4 如果线程daemon属性为False, 则join里的timeout参数无效。主线程会一直等待子线程结束。
import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___')t = threading.Thread(target=say,args=('eve',))t.setDaemon(False)t.start()# t.join(4)print('___主线程结束___')
5 如果线程daemon属性为True, 则join里的timeout参数是有效的, 主线程会等待timeout时间后,结束子线程。此处有一个坑,即如果同时有N个子线程join(timeout),那么实际上主线程会等待的超时时间最长为 N * timeout, 因为每个子线程的超时开始时刻是上一个子线程超时结束的时刻。
例子如下:import threadingimport timedef say(name): print('%s is start ' % name) time.sleep(3) print('%s is stop'%name)print('___主线程开始___')t = threading.Thread(target=say,args=('eve',))t.setDaemon(True)t.start()t.join(4)print('___主线程结束___')
转载于:https://blog.51cto.com/853056088/2162714