python3 停止线程_python3怎么关闭线程
python3利用自定義異常來(lái)退出并關(guān)閉線程。方法:1、利用raise自定義異常;2、當(dāng)觸發(fā)函數(shù)stop_thread時(shí)調(diào)用自定義異常進(jìn)行退出。
利用異常使線程退出代碼如下: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)
補(bǔ)充知識(shí):python threading實(shí)現(xiàn)Thread的修改值,開(kāi)始,運(yùn)行,停止,并獲得內(nèi)部值
總結(jié)
以上是生活随笔為你收集整理的python3 停止线程_python3怎么关闭线程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 三星 Galaxy S24 Ultra
- 下一篇: python检测文件夹中新增文件_pyt