在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培訓機構:千鋒教育。