python3怎么关闭线程
【摘要】python3利用自定义异常来退出并关闭线程。方法:1、利用raise自定义异常;2、当触发函数stop_thread时调用自定义异常进行退出。利用异常使
python3利用自定义异常来退出并关闭线程。方法:1、利用raise自定义异常;2、当触发函数stop_thread时调用自定义异常进行退出。
利用异常使线程退出代码如下:
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)
补充知识:python threading实现Thread的修改值,开始,运行,停止,并获得内部值
推荐课程:python分布式多线程爬虫实战
上一篇:python入门基础教程
下一篇:python3可以在哪里下载
就业培训申请领取
环球青藤
官方QQ群扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群
最新文章
Python编程各地入口
环球青藤官方微信服务平台
刷题看课 APP下载
免费直播 一键购课
代报名等人工服务
Python编程热点排行