这篇文章主要介绍python3关闭线程的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python3利用异常来退出当前线程。方法:1.利用raise自定义异常,2.当触发函数stop_thread时调用自定义异常进行退出。

利用异常使线程退出代码如下:

importinspectimportctypesdef_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)

补充知识:python threading实现Thread的修改值,开始,运行,停止,并获得内部值

以上是python3关闭线程的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!