午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

您的位置:首頁技術文章
文章詳情頁

python中threading開啟關閉線程操作

瀏覽:19日期:2022-07-26 17:00:50

在python中啟動和關閉線程:

首先導入threading

import threading

然后定義一個方法

def serial_read():......

然后定義線程,target指向要執行的方法

myThread = threading.Thread(target=serial_read)

啟動它

myThread.start()

二、停止線程

不多說了直接上代碼

import 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)

停止線程

stop_thread(myThread)

補充知識:python threading實現Thread的修改值,開始,運行,停止,并獲得內部值

下面的半模版代碼在 win7+python3.63 運行通過并且實測可行,為了廣大想要實現python的多線程停止的同學

import threadingimport timeclass MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.Flag=True#停止標志位 self.Parm=0 #用來被外部訪問的 #自行添加參數 def run(self): while(True): if(not self.Flag):break else:time.sleep(2) def setFlag(self,parm): #外部停止線程的操作函數 self.Flag=parm #boolean def setParm(self,parm): #外部修改內部信息函數 self.Parm=parm def getParm(self): #外部獲得內部信息函數 return self.Parm if __name__=='__main__': testThread=MyThread() testThread.setDaemon(True) #設為保護線程,主進程結束會關閉線程 testThread.getParm() #獲得線程內部值 testThread.setParm(1) #修改線程內部值 testThread.start() #開始線程 print(testThread.getParm()) #輸出內部信息 time.sleep(2) #主進程休眠 2 秒 testThread.setFlag(False) #修改線程運行狀態 time.sleep(2) #2019.04.25 修改 print(testThread.is_alive()) #查看線程運行狀態

于2018-08-24修正一次,修正為在繼承thread.Thread時,沒有對父類初始化

舊:

def __init__(self): self.Flag=True#停止標志位 self.Parm=0 #用來被外部訪問的 #自行添加參數

新:

def __init__(self): threading.Thread.__init__(self) self.Flag=True#停止標志位 self.Parm=0 #用來被外部訪問的 #自行添加參數

于2019年4月25日進行第二次修正,發現設置flag值后仍為true輸出的情況,原因是輸出在修改完成前執行,睡眠后結果正常

以上這篇python中threading開啟關閉線程操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 毛片在线网站 | 亚洲精品国产精品国自产网站 | 一级大毛片 | 欧美日韩精品一区二区三区四区 | 成人在线欧美 | 久操精品在线 | 亚洲精品视频专区 | 欧美成人免费在线 | 一区二区三区在线观看免费 | 91黄色在线 | 亚洲人成小说 | 亚洲免费精品视频 | av一二三四区 | 毛片视频播放 | 色噜噜狠狠一区二区三区果冻 | 第四色在线视频 | 一级免费毛片 | 日韩一级一区 | 久久免费资源 | 久久久久久久麻豆 | 亚洲卡一卡二卡三 | 少妇天堂 | 欧美草草| 香蕉精品视频在线观看 | 久青草视频在线观看 | 精品久久久久国产 | 欧美专区在线视频 | 欧美三级视频在线 | a在线天堂| 精品一区二区在线视频 | 久久8 | 日韩av在线免费播放 | 自拍在线观看 | 一级片大全| 亚洲免费视频观看 | 手机av网址 | 免费成人av | 亚洲国产系列 | 福利一区二区 | 国产自产21 | 亚洲人体av |