python怎樣終止線程
在python中啟動和關閉線程:
一、啟動線程
首先導入threading
importthreading
然后定義一個方法
defserial_read():
...
...
然后定義線程,target指向要執行的方法
myThread=threading.Thread(target=serial_read)
啟動它
myThread.start()
二、停止線程
importinspect
importctypes
def_async_raise(tid,exctype):
"""raisestheexception,performscleanupifneeded"""
tid=ctypes.c_long(tid)
ifnotinspect.isclass(exctype):
exctype=type(exctype)
res=ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,ctypes.py_object(exctype))
ifres==0:
raiseValueError("invalidthreadid")
elifres!=1:
#"""ifitreturnsanumbergreaterthanone,you'reintrouble,
#andyoushouldcallitagainwithexc=NULLtoreverttheeffect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,None)
raiseSystemError("PyThreadState_SetAsyncExcfailed")
defstop_thread(thread):
_async_raise(thread.ident,SystemExit)
停止線程
stop_thread(myThread)
stop方法可以強行終止正在運行或掛起的線程。
以上內容為大家介紹了python怎樣終止線程,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。

相關推薦HOT
更多>>
python輸入身高體重算BMI
python輸入身高體重算BMI1、說明身體指標BMI是根據人的身高和重量計算得到的數字指標。它是采集人的身高值(以米為單位)和人體的重量(以公斤為單...詳情>>
2023-11-06 21:34:27
python cmd中怎么運行python文件
運行Python,可在交互模式下運行,或者命令行中。命令行中運行的是Python的.py文件。cmd中執行Python程序的方法,如下打開cmdC:\Users\Administ...詳情>>
2023-11-06 14:37:04
pythondict是啥意思
Python中的dict表示的字典數據類型。字典是另一種可變容器模型,且可存儲任意類型對象。字典是python語言中唯一的映射類型映射類型對象里哈希值...詳情>>
2023-11-06 13:56:05
python如何創建模塊
Python模塊(Module),是一個Python文件,以.py結尾,包含了Python對象定義和Python語句。模塊讓你能夠有邏輯地組織你的Python代碼段。把相關的...詳情>>
2023-11-06 13:36:31