国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python強制關閉線程的一種辦法(可行已用于項目)

2019-11-08 03:22:11
字體:
來源:轉載
供稿:網友

由于經常被Python非Daemon線程阻塞,導致程序無法結束。所以到處找辦法解決,但是經常沒有找到點上。導致無功而返。

今天突發(fā)奇想來搜了一下相關的解決方案,竟然被我找到了。

首先是百度了一下(懶得開VPN)

然后找到了一個網友分享的解決方案:

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

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

然后再次谷歌了一下使用到的API,在最佳回答的評論區(qū)找到了答案。

http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python第六條評論

于是最終解決方案如下:

import threadingimport timeimport inspectimport ctypesdef _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"

附上我的代碼:

    ##將每次訓練任務放到一個獨立的線程中進行,實現(xiàn)多線程    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 函數(shù)最前面,將tid轉換成了c_long類型。因為傳到API中的類型需要是C的長整形,不然會越界。因為在我的環(huán)境中,PID是一個較大的值。

解決方案利用的是python內置API,通過ctypes模塊調用,在線程中丟出異常,使線程退出。

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


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 沂水县| 洪洞县| 阿拉善盟| 新干县| 汉寿县| 商河县| 西乌珠穆沁旗| 叶城县| 大石桥市| 股票| 女性| 开远市| 越西县| 庄浪县| 汨罗市| 苍梧县| 重庆市| 淳化县| 中方县| 罗城| 济宁市| 东方市| 禄丰县| 永平县| 延边| 荣成市| 治县。| 大港区| 浙江省| 宁乡县| 灵武市| 科尔| 通江县| 上林县| 武川县| 巴南区| 米易县| 英吉沙县| 扎赉特旗| 安福县| 兰西县|