首页 > 编程语言 > 详细

python 强制结束线程的坑

时间:2015-11-19 16:16:57      阅读:368      评论:0      收藏:0      [点我收藏+]

网上流传了两种能强制结束线程的错误姿势

第一种:通过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

 

python 强制结束线程的坑

原文:http://www.cnblogs.com/howmp/p/4977668.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!