python3怎么关闭线程

790次阅读
没有评论

python3利用自定义异常来退出并关闭线程。方法:1、利用raise自定义异常;2、当触发函数stop_thread时调用自定义异常进行退出。

python3怎么关闭线程

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

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的修改值,开始,运行,停止,并获得内部值

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-13发表,共计831字。
新手QQ群:570568346,欢迎进群讨论 Python51学习