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使用rsa加密算法模块模拟新浪微博登录
Jan 22 Python
Python字符串替换实例分析
May 11 Python
Python中类型关系和继承关系实例详解
May 25 Python
win与linux系统中python requests 安装
Dec 04 Python
利用django如何解析用户上传的excel文件
Jul 24 Python
Python callable()函数用法实例分析
Mar 17 Python
对TensorFlow中的variables_to_restore函数详解
Jul 30 Python
Python设计模式之工厂方法模式实例详解
Jan 18 Python
我喜欢你 抖音表白程序python版
Apr 07 Python
Django之全局使用request.user.username的实例详解
May 14 Python
python处理写入数据代码讲解
Oct 22 Python
Python之qq自动发消息的示例代码
Feb 18 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
网站当前的在线人数
2006/10/09 PHP
php简单封装了一些常用JS操作
2007/02/25 PHP
PHP中基本符号及使用方法
2010/03/23 PHP
PHP内核探索:哈希表碰撞攻击原理
2015/07/31 PHP
使用WAMP搭建PHP本地开发环境
2017/05/10 PHP
PHP观察者模式原理与简单实现方法示例
2017/08/25 PHP
有关DOM元素与事件的3个谜题
2010/11/11 Javascript
一个JavaScript递归实现反转数组字符串的实例
2014/10/14 Javascript
jQuery实现点击按钮弹出可关闭层的浮动层插件
2015/09/19 Javascript
再谈Javascript中的基本类型和引用类型(推荐)
2016/07/01 Javascript
JavaScript装饰器函数(Decorator)实例详解
2017/03/30 Javascript
jQuery zTree树插件动态加载实例代码
2017/05/11 jQuery
webpack4 css打包压缩问题的解决
2018/05/18 Javascript
JavaScript函数apply()和call()用法与异同分析
2018/08/10 Javascript
在Vue组件中获取全局的点击事件方法
2018/09/06 Javascript
Vue.js实现表格渲染的方法
2018/09/07 Javascript
jquery实现吸顶导航效果
2020/01/08 jQuery
javascript操作向表格中动态加载数据
2020/08/27 Javascript
python根据给定文件返回文件名和扩展名的方法
2015/03/27 Python
Python通过命令开启http.server服务器的方法
2017/11/04 Python
Python随机生成均匀分布在三角形内或者任意多边形内的点
2017/12/14 Python
Python编程实现线性回归和批量梯度下降法代码实例
2018/01/04 Python
Pycharm无法显示动态图片的解决方法
2018/10/28 Python
python使用if语句实现一个猜拳游戏详解
2019/08/27 Python
实现Python与STM32通信方式
2019/12/18 Python
Python使用type动态创建类操作示例
2020/02/29 Python
基于Python正确读取资源文件
2020/09/14 Python
怎样写演讲稿
2014/01/04 职场文书
小松树教学反思
2014/02/11 职场文书
离职报告格式
2014/11/04 职场文书
2015年元旦主持词结束语
2014/12/14 职场文书
师范生小学见习总结
2015/06/23 职场文书
莫言获奖感言(全文)
2015/07/31 职场文书
2016年清明节红领巾广播稿
2015/12/17 职场文书
扩展多台相同的Web服务器
2021/04/01 Servers
解决WINDOWS电脑开机后桌面没有任何图标
2022/04/09 数码科技