Python的子線程和子進程是如何手動結束的?
如何結束Python的子線程和子進程
結束子線程的方法:
這個是搬運其他大神的代碼,鄙人也不知道原理,反正拿來主義,暫時沒發(fā)現(xiàn)什么缺點,先用著再說。
import inspect import ctypes import threading from time import sleep def serial_read(): while True: print("春哥純爺們!") sleep(1) 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) def Air(): ords=0 myThread = threading.Thread(target=serial_read) myThread.start() while True: ords+=1 if ords==10: stop_thread(myThread) print("停止子線程") break sleep(1) if __name__ == '__main__': Air()
下面是結束子進程的方法:
import inspect import ctypes from time import sleep from multiprocessing import Process def serial_read(): while True: print("春哥純爺們!") sleep(1) def Air(): ords=0 myThread = Process(target=serial_read) myThread.start() while True: ords+=1 if ords==10: myThread.terminate() print("停止子進程") break sleep(1) if __name__ == '__main__': Air()
這里說一下如果用類的話要如何寫,想結束子進程或者子線程就需要拿到進程對象或者線程對象,但是類中沒辦法實現(xiàn)創(chuàng)建一個類屬性的方式然后用self.×××的方式來在其他類方法中調用,這時候就創(chuàng)建一個類屬性list,然后創(chuàng)建好子進程或者子線程后把對象賦值給這個list,再在類的其他方法中調用這個list中的元素,就拿到了子進程或者子線程的對象了。
例如:
def startss(self,a1,b1,c1,under,rough,blue,among): # 創(chuàng)建新線程 p1=threading.Thread(target=self.line01,args=(a1,b1,under,rough,)) #必須加,號 p2=threading.Thread(target=self.line02,args=(a1,c1,under,blue,)) p3=Process(target=self.Process01,args=(under,rough,blue,)) #計算進程 #among是類屬性list容器 among.append(p1) among.append(p2) among.append(p3) # 開啟新線程 p1.start() p2.start() #開啟計算用進程 p3.start()
參考資料:http://www.dbjr.com.cn/article/185867.htm
到此這篇關于Python的子線程和子進程是如何手動結束的?的文章就介紹到這了,更多相關Python的子線程和子進程內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python實現(xiàn)兩個list求交集,并集,差集的方法示例
這篇文章主要介紹了Python實現(xiàn)兩個list求交集,并集,差集的方法,結合實例形式分析了Python使用intersection、union及difference方法實現(xiàn)兩個集合list的交集、并集與差集操作技巧,需要的朋友可以參考下2018-08-08Python使用conda如何安裝requirement.txt的擴展包
這篇文章主要介紹了Python使用conda如何安裝requirement.txt的擴展包問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02關于Qt6中QtMultimedia多媒體模塊的重大改變分析
如果您一直在 Qt 5 中使用 Qt Multimedia,則需要對您的實現(xiàn)進行更改。這篇博文將嘗試引導您完成最大的變化,同時查看 API 和內部結構2021-09-09Pycharm連接遠程服務器并實現(xiàn)遠程調試的實現(xiàn)
這篇文章主要介紹了Pycharm連接遠程服務器并實現(xiàn)遠程調試的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08