Python强制关闭线程的一种办法(可行已用于项目)

由于经常被Python非Daemon线程阻塞,导致程序无法结束。所以到处找办法解决,但是经常没有找到点上。导致无功而返。

今天突发奇想来搜了一下相关的解决方案,竟然被我找到了。

首先是百度了一下(懒得开VPN)

然后找到了一个网友分享的解决方案:

http://www.cnblogs.com/rainduck/archive/2013/03/29/2989810.html

但是试验之后并没有什么卵用(┑( ̄Д  ̄)┍),我是在我的MAC上面试验的。python 2.7.10

然后再次谷歌了一下使用到的API,在最佳回答的评论区找到了答案。

http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
第六条评论

于是最终解决方案如下:

import threading
import time
import inspect
import ctypes

def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):
    _async_raise(thread.ident, SystemExit)

class TestThread(threading.Thread):
    def run(self):
        print "begin"
        while True:
            time.sleep(0.1)
        print "end"
if __name__ == "__main__":
    t = TestThread()
    t.start()
    time.sleep(1)
    stop_thread(t)
    print "stoped"


附上我的代码:

    ##将每次训练任务放到一个独立的线程中进行,实现多线程
    def startTrain(self):
        refreshParam()
        self.__threadTrain=threading.Thread(target=self.trainmodel)
        self.train_flag = False
        self.__threadTrain.setDaemon(True)
        self.__threadTrain.start()
#        self.currentthread = self.__threadTrain.getName()
        if not self.train_flag :
            self.periodicTextCall()
        else:
            self.canvas.show()
            self.__threadTrain.stop()
            self.__threadTrain.join()
            self.__threadTrain.exit()
        
        return self.__threadTrain
        
    def stop_trainthread(self):
        trainingthread = self.__threadTrain
        self._async_raise(trainingthread.ident, SystemExit)
        self.StateQueue.put("train stopped.")
        self.train_flag = True
        print 'train stopped.'


改造后的方案,只是在 _async_raise 函数最前面,将tid转换成了c_long类型。因为传到API中的类型需要是C的长整形,不然会越界。因为在我的环境中,PID是一个较大的值。

解决方案利用的是python内置API,通过ctypes模块调用,在线程中丢出异常,使线程退出。

希望我的分享能给各位python程序猿一些帮助。

  • 13
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值