Python强制关闭线程的一种办法(可行

发布时间:2019-08-27 08:00:38编辑:auto阅读(1658)

    由于经常被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程序猿一些帮助。

关键字