python3怎么关闭线程

2020/09/27 08:45

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分布式多线程爬虫实战

免费直播

    精选课程 更多

    注册电脑版

    版权所有 2003-2020 广州环球青藤科技发展有限公司