python3怎么关闭线程
python3" title="python3">python3利用自定义异常来退出并关闭线程。方法:1、利用raise自定义异常;2、当触发函数stop_thread时调用自定义异常进行退出。
利用异常使线程退出代码如下:
import inspectimport 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分布式多线程爬虫实战
以上是 python3怎么关闭线程 的全部内容, 来源链接: utcz.com/z/529718.html