python子线程退出及线程退出控制的代码


Posted in Python onOctober 16, 2019

下面通过代码给大家介绍python子线程退出问题,具体内容如下所示:

def thread_func():
  while True:
      #do something
      #do something
      #do something
t=threading.Thread(target = thread_func)
t.start()
# main thread do something
# main thread do something
# main thread do something

跑起来是没有问题的,但是使用ctrl + c中断的时候出问题了,主线程退出了,但子线程仍然运行。

于是在主线程增加了信号处理的代码,收到sigint时改变子线程循环条件

loop = True
def thread_func():
  while loop:
      #do something
      #do something
      #do something
t=threading.Thread(target = thread_func)
t.start()
# ctrl+c时,改变loop为False
def handler(signum, frame):
  global loop
  loop = False
  t.join()
  exit(0)
signal(SIGINT, handler)
# main thread do something
# main thread do something
# main thread do something

这样ctrl+c就可以退出了,但是疑惑的是,主线程退出进程不会退出吗?

知识点扩展Python线程退出控制

ctypes模块控制线程退出

Python中threading模块并没有设计线程退出的机制,原因是不正常的线程退出可能会引发意想不到的后果。

例如:

线程正在持有一个必须正确释放的关键资源,锁。

线程创建的子线程,同时也将被杀掉。

管理自己的线程,最好的处理方式是拥有一个请求退出标志,这样每个线程依据一定的时间间隔检查规则,看是不是需要退出。

例如下面的代码:

import threading
class StoppableThread(threading.Thread):
  """Thread class with a stop() method. The thread itself has to check
  regularly for the stopped() condition."""

  def __init__(self):
    super(StoppableThread, self).__init__()
    self._stop_event = threading.Event()

  def stop(self):
    self._stop_event.set()

  def stopped(self):
    return self._stop_event.is_set()

这段代码里面,线程应该定期检查停止标志,在退出的时候,可以调用stop()函数,并且使用join()函数来等待线程的退出。

然而,可能会出现确实想要杀掉线程的情况,例如你正在封装一个外部库,它会忙于长时间调用,而你想中断它。

Python线程可以抛出异常来结束:

传参分别是线程id号和退出标识

def _async_raise(tid, exctype):
  '''Raises an exception in the threads with id tid'''
  if not inspect.isclass(exctype):
    raise TypeError("Only types can be raised (not instances)")
  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, 0)
    raise SystemError("PyThreadState_SetAsyncExc failed")

如果线程在python解释器外运行时,它将不会捕获中断,即抛出异常后,不能对线程进行中断。

简化后,以上代码可以应用在实际使用中来进行线程中断,例如检测到线程运行时常超过本身可以忍受的范围。

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)

总结

以上所述是小编给大家介绍的python子线程退出及线程退出控制的代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
matplotlib subplots 设置总图的标题方法
May 25 Python
解决python3 安装完Pycurl在import pycurl时报错的问题
Oct 15 Python
python 将json数据提取转化为txt的方法
Oct 26 Python
python整小时 整天时间戳获取算法示例
Feb 20 Python
为何人工智能(AI)首选Python?读完这篇文章你就知道了(推荐)
Apr 06 Python
python程序快速缩进多行代码方法总结
Jun 23 Python
pygame库实现移动底座弹球小游戏
Apr 14 Python
基于python实现操作git过程代码解析
Jul 27 Python
python实现马丁策略回测3000只股票的实例代码
Jan 22 Python
使用pytorch实现线性回归
Apr 11 Python
python自动化八大定位元素讲解
Jul 09 Python
使用python求解迷宫问题的三种实现方法
Mar 17 Python
python Pillow图像处理方法汇总
Oct 16 #Python
win10环境下配置vscode python开发环境的教程详解
Oct 16 #Python
500行代码使用python写个微信小游戏飞机大战游戏
Oct 16 #Python
python提取xml里面的链接源码详解
Oct 15 #Python
python yield关键词案例测试
Oct 15 #Python
python 发送json数据操作实例分析
Oct 15 #Python
30秒学会30个超实用Python代码片段【收藏版】
Oct 15 #Python
You might like
攻克CakePHP系列一 连接MySQL数据库
2008/10/22 PHP
PHP SPL标准库中的常用函数介绍
2015/05/11 PHP
phpMyAdmin无法登陆的解决方法
2017/04/27 PHP
Laravel 5.4向IoC容器中添加自定义类的方法示例
2017/08/15 PHP
ThinkPHP5.0 图片上传生成缩略图实例代码说明
2018/06/20 PHP
javascript 一个函数对同一元素的多个事件响应
2009/07/25 Javascript
JavaScript 定义function的三种方式小结
2009/10/16 Javascript
javascript textarea光标定位方法(兼容IE和FF)
2011/03/12 Javascript
基于jquery的时间段实现代码
2012/08/02 Javascript
jquery获取iframe中的dom对象(两种方法)
2013/07/02 Javascript
JQuery筛选器全系列介绍
2013/08/27 Javascript
JavaScript 学习笔记之基础中的基础
2015/01/13 Javascript
JavaScript实现多栏目切换效果
2016/12/12 Javascript
localStorage的黑科技-js和css缓存机制
2017/02/06 Javascript
微信小程序 标签传入数据
2017/05/08 Javascript
vue+swiper实现侧滑菜单效果
2017/12/28 Javascript
解决layui的radio属性或别的属性没显示出来的问题
2019/09/26 Javascript
VUE+elementui组件在table-cell单元格中绘制微型echarts图
2020/04/20 Javascript
Node Mongoose用法详解【Mongoose使用、Schema、对象、model文档等】
2020/05/13 Javascript
JS实现简单打字测试
2020/06/24 Javascript
Flask框架的学习指南之制作简单blog系统
2016/11/20 Python
Python读csv文件去掉一列后再写入新的文件实例
2017/12/28 Python
python通过Windows下远程控制Linux系统
2018/06/20 Python
对python 命令的-u参数详解
2018/12/03 Python
Python通用循环的构造方法实例分析
2018/12/19 Python
pandas数据筛选和csv操作的实现方法
2019/07/02 Python
在OpenCV里使用Camshift算法的实现
2019/11/22 Python
python使用QQ邮箱实现自动发送邮件
2020/06/22 Python
scrapy框架携带cookie访问淘宝购物车功能的实现代码
2020/07/07 Python
美国高档百货Nordstrom的折扣店:Nordstrom Rack
2017/11/13 全球购物
总经理职责范文
2013/11/08 职场文书
毕业生自我鉴定
2013/12/04 职场文书
酒鬼酒广告词
2014/03/21 职场文书
美术学专业求职信
2014/07/23 职场文书
党员教师群众路线对照检查材料思想汇报
2014/09/29 职场文书
详解Javascript实践中的命令模式
2021/05/05 Javascript