python 強制結束線程的坑


網上流傳了兩種能強制結束線程的錯誤姿勢

第一種:通過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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM