解决python父线程关闭后子线程不关闭问题


Posted in Python onApril 25, 2020

我们都知道,python可以通过threading module来创建新的线程,然而在创建线程的线程(父线程)关闭之后,相应的子线程可能却没有关闭,这可能是因为代码中没有使用setDaemon(True)函数。

接下来,使用一个例子来说明:

import threading

def prt_hello() :
  while 1 :
    print 'hello'

if __name__ == '__main__' :
  t = threading.Thread(target=prt_hello)
  t.setDaemon(True)
  t.start()

我们需要把setDaemon函数放在start函数前面,不然它是不给通过的,并且返回'cannot set daemon status of active thread‘

补充知识:Python 多线程的退出/停止的一种是实现思路

在使用多线程的过程中,我们知道,python的线程是没有stop/terminate方法的,也就是说它被启动后,你无法再主动去退出它,除非主进程退出了,注意,是主进程,不是线程的父进程.

一个比较合理的方式就是把原因需要放到threading.Thread的target中的线程函数,改写到一个继承类中,下面是一个实现例子

import threading
import time
import os
 
# 原本需要用来启动的无线循环的函数
def print_thread():
  pid = os.getpid()
  counts = 0
  while True:
    print(f'threading pid: {pid} ran: {counts:04d} s')
    counts += 1
    time.sleep(1)
 
# 把函数放到改写到类的run方法中,便可以通过调用类方法,实现线程的终止
class StoppableThread(threading.Thread):
 
  def __init__(self, daemon=None):
    super(StoppableThread, self).__init__(daemon=daemon)
    self.__is_running = True
    self.daemon = daemon
 
  def terminate(self):
    self.__is_running = False
 
  def run(self):
    pid = os.getpid()
    counts = 0
    while self.__is_running:
      print(f'threading running: {pid} ran: {counts:04d} s')
      counts += 1
      time.sleep(1)
 
 
def call_thread():
  thread = StoppableThread()
  thread.daemon = True
  thread.start()
 
  pid = os.getpid()
  counts = 0
  for i in range(5):
    print(f'0 call threading pid: {pid} ran: {counts:04d} s')
    counts += 2
    time.sleep(2)
  # 主动把线程退出
  thread.terminate()
 
 
if __name__ == '__main__':
  call_thread()
  print(f'==========call_thread finish===========')
  counts = 0
  for i in range(5):
    counts += 1
    time.sleep(1)
    print(f'main thread:{counts:04d} s')

以上这篇解决python父线程关闭后子线程不关闭问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python在Windows和在Linux下调用动态链接库的教程
Aug 18 Python
通过Python使用saltstack生成服务器资产清单
Mar 01 Python
利用python批量检查网站的可用性
Sep 09 Python
Python编程实现二分法和牛顿迭代法求平方根代码
Dec 04 Python
Python使用matplotlib绘制随机漫步图
Aug 27 Python
解决每次打开pycharm直接进入项目的问题
Oct 28 Python
Python装饰器限制函数运行时间超时则退出执行
Apr 09 Python
python过滤中英文标点符号的实例代码
Jul 15 Python
Python中的延迟绑定原理详解
Oct 11 Python
解决python -m pip install --upgrade pip 升级不成功问题
Mar 05 Python
python中取绝对值简单方法总结
Jul 24 Python
Python如何爬取51cto数据并存入MySQL
Aug 25 Python
Python标准库:内置函数max(iterable, *[, key, default])说明
Apr 25 #Python
python except异常处理之后不退出,解决异常继续执行的实现
Apr 25 #Python
python 追踪except信息方式
Apr 25 #Python
Python实现捕获异常发生的文件和具体行数
Apr 25 #Python
python IDLE添加行号显示教程
Apr 25 #Python
IDLE下Python文件编辑和运行操作
Apr 25 #Python
python 字典item与iteritems的区别详解
Apr 25 #Python
You might like
全国FM电台频率大全 - 27 陕西省
2020/03/11 无线电
用Socket发送电子邮件
2006/10/09 PHP
调试一段PHP程序时遇到的三个问题
2012/01/17 PHP
PHP反向代理类代码
2014/08/15 PHP
php实现当前页面点击下载文件的实例代码
2016/11/16 PHP
php unicode编码和字符串互转的方法
2020/08/12 PHP
xtree.js 代码
2007/03/13 Javascript
Jquery中Event对象属性小结
2015/02/27 Javascript
轻松掌握JavaScript中的Math object数学对象
2016/05/26 Javascript
AngularJS HTML DOM详解及示例代码
2016/08/17 Javascript
详解Angularjs在控制器(controller.js)中使用过滤器($filter)格式化日期/时间实例
2017/02/17 Javascript
BootStrap点击保存后实现模态框自动关闭的思路(模态框)
2017/09/26 Javascript
微信小程序实现简单input正则表达式验证功能示例
2017/11/30 Javascript
Node.js利用console输出日志文件的方法示例
2018/04/27 Javascript
vue动画打包后失效问题的解决方法
2018/09/18 Javascript
Webpack4 使用Babel处理ES6语法的方法示例
2019/03/07 Javascript
vue v-for 使用问题整理小结
2019/08/04 Javascript
Java 生成随机字符的示例代码
2021/01/13 Javascript
基于python list对象中嵌套元组使用sort时的排序方法
2018/04/18 Python
python进程间通信Queue工作过程详解
2019/11/01 Python
Python中xml和dict格式转换的示例代码
2019/11/07 Python
通过 Django Pagination 实现简单分页功能
2019/11/11 Python
SISLEY希思黎官方旗舰店:享誉全球的奢华植物美容品牌
2018/04/25 全球购物
Ted Baker美国官网:英国时尚品牌
2018/10/29 全球购物
澳大利亚办公室装修:JasonL Office Furniture
2019/06/25 全球购物
说一下mysql, oracle等常见数据库的分页实现方案
2012/09/29 面试题
J2EE包括哪些技术
2016/11/25 面试题
写好求职应聘自荐信的三部曲
2013/09/21 职场文书
什么样的创业计划书可行性高?
2014/02/01 职场文书
中秋节主持词
2014/04/02 职场文书
小学亲子活动总结
2014/07/01 职场文书
公民代理授权委托书
2014/09/24 职场文书
关爱空巢老人感想
2015/08/11 职场文书
web前端之css水平居中代码解析
2021/05/20 HTML / CSS
Java输出Hello World完美过程解析
2021/06/13 Java/Android
深入讲解Vue中父子组件通信与事件触发
2022/03/22 Vue.js