小編給大家分享一下python終止線程的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
在python中啟動和關閉線程:
一、啟動線程
首先導入threading
import threading
然后定義一個方法
def serial_read(): ... ...
然后定義線程,target指向要執行的方法
myThread = threading.Thread(target=serial_read)
啟動它
myThread.start()
二、停止線程
import inspect
import ctypes
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)停止線程
stop_thread(myThread)
stop方法可以強行終止正在運行或掛起的線程。
看完了這篇文章,相信你對python終止線程的方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。