python3关闭线程的方法

发布时间:2020-07-01 16:33:56 作者:清晨
来源:亿速云 阅读:492

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

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

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

推荐阅读:
  1. python中threading怎么开启关闭线程
  2. python父线程关闭后子线程不关闭怎么办

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python3 线程

上一篇:Scrapy项目实战

下一篇:如何在Python中使用input函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》