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 相关文章推荐
Python中关于Sequence切片的下标问题详解
Jun 15 Python
将tensorflow的ckpt模型存储为npy的实例
Jul 09 Python
python 中文件输入输出及os模块对文件系统的操作方法
Aug 27 Python
解决python3.5 正常安装 却不能直接使用Tkinter包的问题
Feb 22 Python
python os模块简单应用示例
May 23 Python
用Python徒手撸一个股票回测框架搭建【推荐】
Aug 05 Python
Python学习笔记之While循环用法分析
Aug 14 Python
TensorFlow自定义损失函数来预测商品销售量
Feb 05 Python
tensorflow之读取jpg图像长和宽实例
Jun 18 Python
python 自定义异常和主动抛出异常(raise)的操作
Dec 11 Python
详解分布式系统中如何用python实现Paxos
May 18 Python
Python学习之os包使用教程详解
Mar 21 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
PHP设计模式之观察者模式实例
2016/02/22 PHP
PHP环形链表实现方法示例
2017/09/15 PHP
php使用mysqli和pdo扩展,测试对比mysql数据库的执行效率完整示例
2019/05/09 PHP
解析js如何获取当前url中的参数值并复制给input
2013/06/23 Javascript
随鼠标移动的时钟非常漂亮遗憾的是只支持IE
2014/08/12 Javascript
Egret引擎开发指南之运行项目
2014/09/03 Javascript
js实现鼠标滚轮控制图片缩放效果的方法
2015/02/20 Javascript
js实现漂浮回顶部按钮实例
2015/05/06 Javascript
JS+DIV+CSS实现仿表单下拉列表效果
2015/08/18 Javascript
JS实现网页顶部向下滑出的全国城市切换导航效果
2015/08/22 Javascript
js将json格式的对象拼接成复杂的url参数方法
2016/05/25 Javascript
js实现百度登录框鼠标拖拽效果
2017/03/07 Javascript
jQuery实现点击关注和取消功能
2017/07/03 jQuery
JS实现颜色的10进制转化成rgba格式的方法
2017/09/04 Javascript
AngularJS中ng-options实现下拉列表的数据绑定方法
2018/08/13 Javascript
JS根据Unix时间戳显示发布时间是多久前【项目实测】
2019/07/10 Javascript
Vue+Vant 图片上传加显示的案例
2020/11/03 Javascript
[32:17]完美世界DOTA2联赛循环赛LBZS vs Forest第二场 10月30日
2020/10/31 DOTA
[47:45]DOTA2-DPC中国联赛 正赛 Phoenix vs Dragon BO3 第一场 2月26日
2021/03/11 DOTA
python使用ctypes模块调用windowsapi获取系统版本示例
2014/04/17 Python
Python使用CMD模块更优雅的运行脚本
2015/05/11 Python
Django应用程序中如何发送电子邮件详解
2017/02/04 Python
Python程序退出方式小结
2017/12/09 Python
使用python实现微信小程序自动签到功能
2020/04/27 Python
解决使用Pandas 读取超过65536行的Excel文件问题
2020/11/10 Python
基于html和CSS3制作酷炫的导航栏
2015/09/23 HTML / CSS
巧用HTML5给按钮背景设计不同的动画简单实例
2016/08/09 HTML / CSS
微软马来西亚官方网站:Microsoft马来西亚
2019/11/22 全球购物
Nike墨西哥官网:Nike MX
2020/08/30 全球购物
小学教师自我鉴定范文
2014/03/20 职场文书
网上祭先烈心得体会
2014/09/01 职场文书
如何写贫困证明申请书
2014/10/29 职场文书
傲慢与偏见电影观后感
2015/06/10 职场文书
最新农村养殖致富:资金投入较低的创业项目有哪些?
2019/09/26 职场文书
Redis 操作多个数据库的配置的方法实现
2022/03/23 Redis
Python进程间的通信之语法学习
2022/04/11 Python