Python的threading 本身没有提供.kill()方法来结束线程。但是只需要一个小小的变通就可以实现。
一个caller线程在里面调用需要控制时间的tHhandle线程并把tHhandle线程设置.setDaemon()方法为True。caller线程结束,tHandle线程就会跟着结束。
# encoding: UTF-8import threadingimport time#完全原生强制结束python线程的方法。转载请注明来自博客园def func(tHandle,timeout): #caller 函数 print 'in time control.' tHandle.setDaemon(True) #设置tHandle线程为daemon,关键地方!! tHandle.start()# 让tHandle线程进入阻塞状态 tHandle.join(timeout) #tHandle 有timeout这么多秒的时间运行之后进入阻塞(也可以认为是挂起) print 'out time control' #这句执行完毕后,由于tHandle线程是此线程的守护程序 #因此caller结束后tHandle也就结束了,从而达到kill tHandle线程的目的def checkproxy(timewait,timewait2): print 'in checkproxy.' time.sleep(timewait) time.sleep(timewait2) print 'out checkproxy.' #这句在此例子里是不运行的,因为此句要在20+1=21秒之后运行, #但是caller 只给了2秒时间运行,然后caller结束,此线程也要结束。所以运行不到tcheck = threaking.Thread(target=checkproxy,args=(1,20,))caller=threading.Thread(target=func,args=(tcheck,2,))caller.start()#运行结果:#in time control.#in checkproxy.#out time control |
浙公网安备 33010602011771号