Python Thread related
1.Thread.join([timeout])
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
等待进程结束。也就是说,其屏蔽调用线程,直到此线程方法终止(要么正常执行完毕,或者未处理的异常,或者时间超时)
下面通过例子来说明:
没有设定timeout情况,Main 线程启动,work1 和work2 线程执行,完毕退出,Main线程执行终止
1 import os 2 import threading 3 import time 4 import logging 5 import random 6 7 def work1(): 8 count=0 9 while count<=5: 10 threadname= threading.currentThread() 11 wait_time=random.randrange(1,4) 12 print("%s,count =%s wait for =%s s,time %s "%(threadname,count,wait_time,time.ctime()[-13:])) 13 time.sleep(wait_time) 14 count +=1 15 16 def work2(): 17 i=0 18 while i<=5: 19 threadname= threading.currentThread() 20 wait_time=random.randrange(1,4) 21 print("%s,i =%s wait for =%s s,time %s "%(threadname,i,wait_time,time.ctime()[-13:])) 22 time.sleep(wait_time) 23 i +=1 24 25 if __name__ =="__main__": 26 mainthread= threading.currentThread() 27 print '%s main thread is waiting for exit'% mainthread 28 test1=threading.Thread(name='work1',target=work1) 29 test2=threading.Thread(name='work2',target=work2) 30 test1.start() 31 test2.start() 32 test1.join() 33 test2.join() 34 print 'main thread finish'
2个线程设定超时时间work1 5s,work2 4s,9s之后调用线程结束而不等待超时的线程:
1 import os 2 import threading 3 import time 4 import logging 5 import random 6 7 def work1(): 8 count=0 9 while count<=5: 10 threadname= threading.currentThread() 11 wait_time=random.randrange(1,4) 12 print("%s,count =%s wait for =%s s,time %s "%(threadname,count,wait_time,time.ctime()[-13:])) 13 time.sleep(wait_time) 14 count +=1 15 16 def work2(): 17 i=0 18 while i<=5: 19 threadname= threading.currentThread() 20 wait_time=random.randrange(1,4) 21 print("%s,i =%s wait for =%s s,time %s "%(threadname,i,wait_time,time.ctime()[-13:])) 22 time.sleep(wait_time) 23 i +=1 24 25 if __name__ =="__main__": 26 mainthread= threading.currentThread() 27 print '%s main thread is waiting for exit'% mainthread 28 test1=threading.Thread(name='work1',target=work1) 29 test2=threading.Thread(name='work2',target=work2) 30 test1.start() 31 test2.start() 32 test1.join(4) 33 test2.join(5) 34 print 'main thread finish