国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python中threading開啟關(guān)閉線程操作

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

在python中啟動(dòng)和關(guān)閉線程:

首先導(dǎo)入threading

import threading

然后定義一個(gè)方法

def serial_read():......

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

myThread = threading.Thread(target=serial_read)

啟動(dòng)它

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)

補(bǔ)充知識(shí):python threading實(shí)現(xiàn)Thread的修改值,開始,運(yùn)行,停止,并獲得內(nèi)部值

下面的半模版代碼在 win7+python3.63 運(yùn)行通過并且實(shí)測(cè)可行,為了廣大想要實(shí)現(xiàn)python的多線程停止的同學(xué)

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

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

舊:

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

新:

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

于2019年4月25日進(jìn)行第二次修正,發(fā)現(xiàn)設(shè)置flag值后仍為true輸出的情況,原因是輸出在修改完成前執(zhí)行,睡眠后結(jié)果正常

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

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 阿克苏市| 鄂州市| 平舆县| 郧西县| 阳朔县| 乌拉特后旗| 耒阳市| 宝坻区| 临沂市| 通榆县| 襄城县| 闻喜县| 伊吾县| 石景山区| 灵璧县| 丹东市| 藁城市| 三门峡市| 罗甸县| 水城县| 杭锦后旗| 和平县| 台湾省| 新郑市| 汉中市| 岳西县| 成安县| 依兰县| 庆城县| 安宁市| 平邑县| 屏山县| 凤庆县| 年辖:市辖区| 曲沃县| 正定县| 绵阳市| 东宁县| 临朐县| 尖扎县| 中牟县|