解决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 (1)
Oct 31 Python
python搭建简易服务器分析与实现
Dec 15 Python
浅谈python类属性的访问、设置和删除方法
Jul 25 Python
插入排序_Python与PHP的实现版(推荐)
May 11 Python
Python tkinter的grid布局及Text动态显示方法
Oct 11 Python
浅谈Python中的bs4基础
Oct 21 Python
Python中模块(Module)和包(Package)的区别详解
Aug 07 Python
30秒学会30个超实用Python代码片段【收藏版】
Oct 15 Python
使用Tensorflow实现可视化中间层和卷积层
Jan 24 Python
使用opencv中匹配点对的坐标提取方式
Jun 04 Python
Python实现对word文档添加密码去除密码的示例代码
Dec 29 Python
python3实现Dijkstra算法最短路径的实现
May 12 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
改写函数实现PHP二维/三维数组转字符串
2013/09/13 PHP
Centos PHP 扩展Xchche的安装教程
2016/07/09 PHP
JavaScript Event学习第九章 鼠标事件
2010/02/08 Javascript
json-lib出现There is a cycle in the hierarchy解决办法
2010/02/24 Javascript
javascript 异步页面查询实现代码(asp.net)
2010/05/26 Javascript
通过上下左右键和回车键切换光标实现代码
2013/03/08 Javascript
jQuery 过滤方法filter()选择具有特殊属性的元素
2014/06/15 Javascript
一个很有趣3D球状标签云兼容IE8
2014/08/22 Javascript
js+canvas绘制矩形的方法
2016/01/28 Javascript
jQuery实现大图轮播
2017/02/13 Javascript
jQuery中$原理实例分析
2018/08/13 jQuery
React router动态加载组件之适配器模式的应用详解
2018/09/12 Javascript
JS实现查找数组中对象的属性值是否存在示例
2019/05/24 Javascript
[02:36]DOTA2英雄基础教程 斯拉克
2013/11/29 DOTA
[02:25]DOTA2英雄基础教程 熊战士
2014/01/03 DOTA
[56:35]DOTA2上海特级锦标赛C组小组赛#1 OG VS Archon第二局
2016/02/27 DOTA
Python实现从url中提取域名的几种方法
2014/09/26 Python
python入门基础之用户输入与模块初认识
2016/11/14 Python
Python wxpython模块响应鼠标拖动事件操作示例
2018/08/23 Python
Python地图绘制实操详解
2019/03/04 Python
django 捕获异常和日志系统过程详解
2019/07/18 Python
python遍历文件目录、批量处理同类文件
2019/08/31 Python
有趣的Python图片制作之如何用QQ好友头像拼接出里昂
2020/04/22 Python
浅谈tensorflow使用张量时的一些注意点tf.concat,tf.reshape,tf.stack
2020/06/23 Python
Python浮点型(float)运算结果不正确的解决方案
2020/09/22 Python
利用python爬取有道词典的方法
2020/12/08 Python
H5 canvas实现贪吃蛇小游戏
2017/07/28 HTML / CSS
解析html5 canvas实现背景鼠标连线动态效果代码
2019/06/17 HTML / CSS
动物学专业毕业生求职信
2013/10/11 职场文书
加工操作管理制度
2014/01/19 职场文书
初一体育教学反思
2014/01/29 职场文书
运动会稿件100字
2014/02/21 职场文书
2014学习全国两会精神心得体会2000字
2014/03/11 职场文书
初中团支书竞选稿
2015/11/21 职场文书
2016年共产党员公开承诺书
2016/03/24 职场文书
创业计划书之农家乐
2019/10/09 职场文书