網上流傳了兩種能強制結束線程的錯誤姿勢
第一種:通過setDaemon來結束線程
http://www.cnblogs.com/jefferybest/archive/2011/10/09/2204050.html
import threading import time def mythread(timeout,func): tHandle = threading.Thread(target=func) tHandle.setDaemon(True) tHandle.start() tHandle.join(timeout) print 'timeout' def do(): while 1: time.sleep(0.2) print 'thread runing' caller=threading.Thread(target=mythread,args=(1,do)) caller.start() time.sleep(10)
運行結果,並不會結束。因為setDaemon按照我的理解只跟主線程相關
thread runing
thread runing
thread runing
thread runing
timeout
thread runing
thread runing
thread runing
thread runing
thread runing
thread runing
thread runing
thread runing
第二種通過threading.Thread._Thread__stop()結束線程
import time import threading def f(): while 1: time.sleep(0.1) print 1 t = threading.Thread(target=f) t.start() time.sleep(0.5) print "Stopping the thread" threading.Thread._Thread__stop(t) print "Stopped the thread" while 1: time.sleep(0.1) print t.isAlive()
運行結果如下:猜測是_Thread__stop只是設置了線程結束的標記,並沒有真正結束線程
1 1 1 1 Stopping the thread Stopped the thread 1 False 1 False 1 False 1 False 1 False 1 False 1 False 1 False 1 False 1 False 1 False 1 False 1