iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python强制关闭线程的一种办法(可行
  • 902
分享到

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

线程办法Python 2023-01-31 02:01:15 902人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

由于经常被python非Daemon线程阻塞,导致程序无法结束。所以到处找办法解决,但是经常没有找到点上。导致无功而返。 今天突发奇想来搜了一下相关的解决方案,竟然被我找到了。 首先是百度了一下(懒得开VPN) 然后找到了一个网友分

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

--结束END--

本文标题: Python强制关闭线程的一种办法(可行

本文链接: https://www.lsjlt.com/news/186462.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作