python 强制结束线程的坑

时间:2023-03-09 03:28:57
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